刷题笔记:leetcode第6题:ZigZag Conversion

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37590135/article/details/80140571

记录一下~~

    问题:



思路:由于字符串可能很大,消耗计算量的做法肯定是不能用的,最后只遍历一次,然后拼接入二维数组

        1、遍历每个字符

        2、设定自加型偏移量,自动放入

        3、StringBuffer顺序接收以后输出;

代码如下:

class Solution {
    public String convert(String s, int numRows) {
        if(s.equals("") || s == null ) return "";
        if(numRows <= 1) return s;
        
        char[] c = s.toCharArray();
        int w = (c.length/(numRows*2-2)+1)*(numRows-1) + 1;
        char[][] a = new char[numRows][w];
        int offset = 0;
        for(int i = 0;i<c.length ;i++){
            for(;;offset++){
                int woff = offset/numRows;
                int hoff = offset%numRows;
                if(woff%(numRows-1) == 0 || (woff+hoff)%(numRows-1) == 0){
                    a[hoff][woff] = c[i];
                    offset++;
                    break;
                }
            }
        }

        StringBuffer sb = new StringBuffer("");
        for(int i = 0 ; i< numRows ; i++){
            for(int j = 0 ; j< w ; j++){
                if(a[i][j] != 0) sb.append(a[i][j]);
            }
        }

        return sb.toString();
    }
}


猜你喜欢

转载自blog.csdn.net/m0_37590135/article/details/80140571