forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ZigZagConverstion.swift
41 lines (34 loc) · 1.13 KB
/
ZigZagConverstion.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* Question Link: https://leetcode.com/problems/zigzag-conversion/
*
* Primary idea: The first and the last row, loop length is (2 * numRows - 2)
* For each row between them, should insert another number, index = index + 2 * (numRows - i - 1)
*
* Time Complexity: O(log(n + m)), Space Complexity: O(1)
*
*/
class Solution {
func convert(s: String, _ numRows: Int) -> String {
if numRows == 1 {
return s
}
var ret: [Character] = []
var chars: [Character] = [Character](s.characters)
let cnt = chars.count
for i in 0..<numRows {
let len = 2 * numRows - 2
var index = i
while index < cnt {
ret.append(chars[index])
if i != 0 && i != numRows - 1 {
let tmpIndex = index + 2 * (numRows - i - 1)
if tmpIndex < cnt {
ret.append(chars[tmpIndex])
}
}
index += len
}
}
return String(ret)
}
}