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

class Solution {
    public String convert(String s, int numRows) {
        if(numRows == 1) return s;
        int len = s.length();
        if(len <= numRows) return s;
        StringBuilder sb = new StringBuilder();
        
        int j = 0;
        int step = 0;
        int sum = (numRows - 1) << 1;
        for(int i = 0; i< numRows ; i++){
            //int sum = 2 * (numRows - 1); 
            //int step = 2 * i;
            step = i << 1;
            for(j = i; j < len; j += step){
                sb.append(s.charAt(j));
                
                step = sum - step;
                if(step==0) 
                    step = sum - step;
            }
        }
        
        return sb.toString();
        
    }
}

z字形的边是平行的,中间是对角线.可以理解为每一行的步长是变长的.如果v的最大间隔为n,那么必然存在第i行:步长在n-2i 和2i 之间交替

算法一般,偷偷开了俩外挂,StringBuilder 和位运算>.<

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容