Leetcode日记(6)---ZigZag Conversion

Leetcode日记(6)---ZigZag Conversion_第1张图片

首行距2*(nRows-1)

代码分析参照上面的图

//通过的代码
class Solution {
public:
    string convert(string s, int numRows) {
        if(numRows<2 || s.size()<=numRows) return s;
        string res(s.size(),0);
        char *p=&res[0];
        for(int i=0, j,k, step=(numRows-1)*2;i<numRows;++i) {
            if(i==0 || i==numRows-1) 
                for(j=i;j<s.size();j+=step) *p++=s[j];
            else
                for(j=i, k=i<<1;j<s.size();k=step-k,j+=k) *p++=s[j];
        }
        return res;
    }
};
public class Solution {
    public String convert(String s, int nRows) {
        int len = s.length();
        if (len == 0 || nRows <= 1) return s;

        String[] ans = new String[nRows];
        Arrays.fill(ans, "");
        int row = 0, delta = 1;
        for (int i = 0; i < len; i++) {
            ans[row] += s.charAt(i);
            row += delta;
            if (row >= nRows) {
                row = nRows-2;
                delta = -1;
            }
            if (row < 0) {
                row = 1;
                delta = 1;
            }
        }

        String ret = "";
        for (int i = 0; i < nRows; i++) {
            ret += ans[i];
        }
        return ret;
    }
}

你可能感兴趣的:(LeetCode)