leetcode6---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)

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".
题目分析:返回一个字符串的类似于"Z"字形走法,没有想到什么别的方法。模拟步骤走一遍就能得出结果。

    public String convert(String s, int numRows) {
        if (s == null)
            return null;
        if (s.length() <= 1)
            return s;
        StringBuffer[] sbs = new StringBuffer[numRows];
        for (int i = 0; i < sbs.length; i++) {
            sbs[i] = new StringBuffer();
        }
        int j = 0;
        while (j < s.length()) {
            for (int i = 0; i < numRows; i++) {
                if (j < s.length()) {
                    char c = s.charAt(j++);
                    sbs[i].append(c);
                } else {
                    break;
                }
            }

            for (int l = numRows - 2; l > 0; l--) {
                if (j < s.length()) {
                    char c = s.charAt(j++);
                    sbs[l].append(c);
                } else {
                    break;
                }
            }
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < numRows; i++) {
            sb.append(sbs[i]);
        }
        return sb.toString();
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,788评论 0 33
  • 6. ZigZag Conversion The string "PAYPALISHIRING" is writt...
    LdpcII阅读 319评论 0 0
  • 一、Masonry介绍 之前我们在屏幕适配的章节中学习过AutoLayout的使用,但那都是在可视化界面上进行添加...
    无沣阅读 2,157评论 0 1
  • 《草房子》里所有的题目里都有桑桑,这桑桑真像一只小松鼠,从这个题目蹦到那个题目,又从那个题目蹦到这个题目,他在每个...
    勿忘我578阅读 449评论 0 1
  • T-SQL中使用中括号或者双引号,来将不合法字符序列看做标识符。例如User是SQL Server的关键字,使用[...
    何幻阅读 853评论 0 0