ZigZag Conversion

22 篇文章 0 订阅
6 篇文章 0 订阅
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
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值