Problem 6

ZigZag Coversion

Posted by Ruizhi Ma on July 11, 2019

问题描述

https://leetcode.com/problems/zigzag-conversion/

解决思路

就不讲了,感觉没什么借鉴意义这个题。有兴趣去youtube看篮子王的讲解吧。

代码

class Solution {
    public String convert(String s, int numRows) {
        char[] c = s.toCharArray();
        int len = c.length;
        
        StringBuilder[] sb = new StringBuilder[numRows];
        
        //initialize the StringBuilder
        for(int i = 0; i < sb.length; i++){
            sb[i] = new StringBuilder();
        }
        
        int i = 0;
        
        while(i < len){
            //vertically down
            for(int index = 0; index < numRows && i < len; index++){
                sb[index].append(c[i++]); 
            }
            //obliquely up
            for(int index = numRows - 2; index >= 1 && i < len; index--){
                sb[index].append(c[i++]);
            }
        }
        
        //merge StringBuilder to output the string
        for(int index = 1; index < sb.length; index++){
            sb[0].append(sb[index]);
        }
        
        return sb[0].toString();
    }
}

效率探究

时间效率:O(n^2)
空间效率:O(n^2)