题目链接:https://leetcode-cn.com/problems/zigzag-conversion/
执行用时:48 ms, 在所有 Swift 提交中击败了91.49% 的用户
内存消耗:14.3 MB, 在所有 Swift 提交中击败了21.28% 的用户
通过测试用例:1157 / 1157
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Solution { func convert(_ s: String, _ numRows: Int) -> String { guard numRows > 1 else { return s } var arr = [String].init(repeating: "", count: numRows) var str = Array(s) var cursor = 0, move = -1 for ch in str { arr[cursor].append(ch) if cursor == 0 || cursor == numRows - 1 { move = -move } cursor += move } return arr.joined() } }
|
执行用时:4 ms, 在所有 Java 提交中击败了82.25% 的用户
内存消耗:42.1 MB, 在所有 Java 提交中击败了10.85% 的用户
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution { public String convert(String s, int numRows) { if (numRows == 1) { return s; } StringBuilder[] sbs = new StringBuilder[numRows]; int cursor = 0, down = -1; StringBuilder res = new StringBuilder(); for(int i = 0; i < numRows; i++) { sbs[i] = new StringBuilder(); } for (char ch: s.toCharArray()) { sbs[cursor].append(ch); if (cursor == 0 || cursor == numRows -1) { down = - down; } cursor += down; } for (StringBuilder str: sbs) { res.append(str); } return res.toString(); } }
|