leetcode 6. N 字形变换

    public String convert(String s, int numRows) {
        if (s.isEmpty() || s == null || numRows >= s.length() || numRows == 1) {
            return s;
        }

        int n = s.length();
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= numRows; i++) {
            int j = i - 1;
            if ((i > 1) && (i < numRows)) {
                sb.append(s.charAt(j));
                while (true) {
                    if (j + (numRows - i) * 2 >= n) {
                        break;
                    }
                    sb.append(s.charAt(j + (numRows - i) * 2));

                    if (j + 2 * numRows - 2 >= n) {
                        break;
                    }
                    j = j + 2 * numRows - 2;
                    sb.append(s.charAt(j));
                }
            } else {
                sb.append(s.charAt(j));
                while ((j + 2 * numRows - 2) < n) {
                    j = j + 2 * numRows - 2;
                    sb.append(s.charAt(j));
                }
            }
        }
        return sb.toString();
    }

贴一个别人的解法

    public String convert(String s, int numRows) {
        if(numRows < 2) return s;
        List<StringBuilder> rows = new ArrayList<StringBuilder>();
        for(int i = 0; i < numRows; i++) rows.add(new StringBuilder());
        int i = 0, flag = -1;
        for(char c : s.toCharArray()) {
            rows.get(i).append(c);
            if(i == 0 || i == numRows -1) flag = - flag;
            i += flag;
        }
        StringBuilder res = new StringBuilder();
        for(StringBuilder row : rows) res.append(row);
        return res.toString();
    }

posted @ 2023-02-15 16:53  jrjewljs  阅读(75)  评论(0编辑  收藏  举报