首页 > 代码库 > [jeetcode]ZigZag Conversion

[jeetcode]ZigZag Conversion

这道题目属于比较简单的,但是仍然要注意空间复杂度,比较好的解法是运用数学手段,发现规律。

public class Solution {    public String convert(String s, int nRows) {        int len = s.length();        if (len <= nRows || nRows == 1) {            return s;        } else {            String res = "";            int num = 0;            for (int r = 0; r < nRows; r++) {                int count = 0;                num = r;                while (num < len) {                    res = res + s.charAt(num);                    count = count + 1;                    if (r == 0 || r == nRows - 1) {                        num = num + 2 * (nRows - 1);                    } else {                        if (count % 2 == 1) {                            num = num + 2 * (nRows - r - 1);                        } else {                            num = num + 2 * r;                        }                    }                }            }            return res;    }    }}

 

[jeetcode]ZigZag Conversion