6. ZigZag Conversion

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)

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

Solution

找规律

class Solution {
    public String convert(String s, int numRows) {
        if (s == null || numRows < 1) {
            return null;
        }
        
        StringBuilder sb = new StringBuilder();
        int largeStep = Math.max((numRows - 1) << 1, 1);    // important
        int smallStep = largeStep;
        
        for (int i = 0; i < numRows; ++i) {
            for (int j = i; j < s.length(); j += largeStep) {
                sb.append(s.charAt(j));
                if (smallStep > 0 && smallStep < largeStep 
                        && j + smallStep < s.length()) {
                    sb.append(s.charAt(j + smallStep));
                }
            }
            smallStep -= 2;
        }
        
        return sb.toString();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,472评论 0 23
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 7,946评论 0 0
  • 年会报名开始的时候,还没有计划参加,隔周两天的川大上课,让我已经2个月没有休息过周末,刚好年会那周想好好休息陪...
    分享则快乐阅读 2,312评论 0 0
  • 想了很久很久,终于给自己找到一个理由 一份来自前世的缘份 一份飞蛾扑火的追随 一份满心成全、呵护的情 一份执着、从...
    欣赏就会珍惜阅读 1,423评论 0 0
  • 在过去一年最流行的一句话大概就是“世界那么大,我想去看看“了。 这句话到底引起来多少人心血来潮辞职来一场说...
    童童小瑾书阅读 2,860评论 0 0