[LeetCode] 006.ZigZag Conversion (Java)

Problem description

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)

P   A   H   N
A P L S I I G
Y   I   R

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".

Code

class Solution {
    public String convert(String s, int numRows) {
        
        String[] res = new String[numRows];
        for(int i = 0; i < numRows; i++) {
            res[i] = "";
        }
        int len = s.length();
        
        if(len == 0) {
            return "";
        } 
        
        int l = 0;
        int point = 0;
        
        while(l < len) {
            if(numRows >= 3) {
                if(point == 0) {
                    for(int i = 0; i < numRows; i++) {
                        if(l == len) {
                            break;
                        }
                        res[point++] += s.charAt(l++);
                    }
                    point -= 2;
                } else {
                    res[point--] += s.charAt(l++);
                }  
            } else {
                for(int i = 0; i < numRows; i++) {
                    if(l == len) {
                        break;
                    }
                    res[i] += s.charAt(l++);
                }
            }
                                
        }
        String ss = "";
        for(int i = 0; i < numRows; i++) {
            ss += res[i];
        }
        return ss;
    }
}

Analysis

  • String數(shù)組主要初始化。
最后編輯于
?著作權(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)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,170評論 0 23
  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,927評論 0 33
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc閱讀 2,995評論 0 0
  • 01 一天,我們團隊的幾個人一起吃飯,說起工作的事情,團隊負責(zé)人表達了他的認識。他只是以自己過往的工作為例子,認為...
    夜語山林閱讀 593評論 0 2
  • 感謝 在孤單的時候 你說,還有我 感謝 在低落的時候 你說,別害怕 感謝 在寒冷的風(fēng)里 看到你的微笑 感謝 有你站...
    歡樂V英雄閱讀 310評論 0 3

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