ZigZag Conversion

来源:互联网 发布:传奇单机版物品数据库 编辑:程序博客网 时间:2024/05/18 03:19
public class Solution {    public String convert(String s, int nRows) {        int len = s.length();//len即为字符串长度        if(len<=nRows||nRows<=1) return s; //such condition can't form the zigzag route.        //以上两种情况都可以直接返回该字符串        StringBuilder[] result = new StringBuilder[nRows]; //string buffer array to hold each row's result        //定义一个SringBuider的array,用来存放结果,长度为nRows        //initialize the string buffer        for(int i = 0; i < result.length; i++){            result[i] = new StringBuilder();        }        //不明白上面为什么一定要初始化        //divide the groups into chunks with size (nRows*2-2).        int chunk = nRows*2-2; //3->4, 4->6, 5->7, etc.        //chunk就是周期的长度        for(int i = 0; i < len; i++){            int group = i%chunk; //get the index of the element in the chunk            //利用zigzag的周期性,将所有元素放入不同的group中。同group的元素必定在同一行,但有的行会包含两个group的元素。            //if they are less then nRows, this element is vertically aligned from top to buttom            if(group<nRows){                result[group].append(s.charAt(i));            }        //以上代码针对竖排元素的归类,利用append可以向每个StringBuilder group添加元素        //otherwise, it falls onto the slope in reversed direction            else{                result[chunk-group].append(s.charAt(i));            }        //对于斜排的元素chunk-group,就能找到同行对应的group的元素        }        //combine the groups into final array.        StringBuilder sb = new StringBuilder();        for(int i = 0; i < nRows; i++){            sb.append(result[i].toString());        }        //利用另一个string builder把之前的几个result里的每个元素连起来就是答案了        return sb.toString();//把StringBuilder转为string    }}
0 0