[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数组主要初始化。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,501评论 0 23
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,357评论 0 33
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 7,956评论 0 0
  • 01 一天,我们团队的几个人一起吃饭,说起工作的事情,团队负责人表达了他的认识。他只是以自己过往的工作为例子,认为...
    夜语山林阅读 3,558评论 0 2
  • 感谢 在孤单的时候 你说,还有我 感谢 在低落的时候 你说,别害怕 感谢 在寒冷的风里 看到你的微笑 感谢 有你站...
    欢乐V英雄阅读 1,846评论 0 3

友情链接更多精彩内容