leetcode的每日一題更新(ZigZag Conversion)

題目:The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
意思就是大概就是

S.png

給一個字符串和行數(shù),倒Z排列好了以后,最后返回的字符串是所有的行拼接起來的。abcdefghijklmn,numRows=5,輸出字符為aibhjcgkdflnem
思路:一開始就想好了把上下和中間分隔開來,這樣就簡單一點,上和下的代碼都一樣,只是循環(huán)的起點不一樣,距離都是numRows+numRows-2,中間有點麻煩,剛開始想錯了,以為它每一丨都是從上到下依次的來,寫完提交以后才發(fā)現(xiàn)是z字形的,然后只要重寫中間的代碼就行,仔細看了一下中間的數(shù)字規(guī)律就是:第一個字母不用說是i,第二個是(numRows-i)2,第三個是i2-1,然后又是(numRows-i)*2,一直循環(huán),想了想只能靠一個boolean來控制這樣的轉(zhuǎn)換用來控制取字母的循環(huán)變量。附上我的代碼:

    public String convert(String s, int numRows) {
        if(s=="")return "";
        if(numRows<2)return s;
        String result="";
        
        boolean bian=true;
        for(int i=0;i<s.length();i+=numRows+numRows-2) {
                result+=s.charAt(i);
        }
        for(int i=1;i<numRows-1;i++) {
            for(int j=i;j<s.length();j++) {
                result+=s.charAt(j);
                if(bian) {j+=(numRows-i-1)*2-1;bian=false;continue;}
                if(!bian) {j+=i*2-1;bian=true;}
            }
            bian=true;
        }
        for(int i=numRows-1;i<s.length();i+=numRows+numRows-2) {
            result+=s.charAt(i);
        }
        return result;
    }

測試了一下別人的代碼和我的代碼,別人用了1ms,我用了18。。。。。
好好研究學(xué)習(xí)一下,這一篇文章就這樣

    public String convert(String s, int nRows) {
        char[] c = s.toCharArray();
        int len = c.length;
        StringBuffer[] sb = new StringBuffer[nRows];
        for (int i = 0; i < sb.length; i++) sb[i] = new StringBuffer();
        
        int i = 0;
        while (i < len) {
            for (int idx = 0; idx < nRows && i < len; idx++) // vertically down
                sb[idx].append(c[i++]);
            for (int idx = nRows-2; idx >= 1 && i < len; idx--) // obliquely up
                sb[idx].append(c[i++]);
        }
        for (int idx = 1; idx < sb.length; idx++)
            sb[0].append(sb[idx]);
        return sb[0].toString();
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容