The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
Answer:
private extension String {
/*
Ref: http://oleb.net/blog/2014/07/swift-strings/
"Because of the way Swift strings are stored, the String type does not support random access to its Characters via an integer index — there is no direct equivalent to NSStringʼs characterAtIndex: method. Conceptually, a String can be seen as a doubly linked list of characters rather than an array."
By creating and storing a seperate array of the same sequence of characters,
we could hopefully achieve amortized O(1) time for random access.
*/
func randomAccessCharactersArray() -> [Character] {
return Array(self.characters)
}
}
class Solution {
func convert(_ s: String, _ numRows: Int) -> String {
var arr = Array<String>(repeating: String(), count: numRows)
var i = 0
let charArr = s.randomAccessCharactersArray()
let len = charArr.count
while i < len {
var index = 0
while index < numRows && i < len {
arr[index].append(charArr[i])
i += 1
index += 1
}
index = numRows - 2
while index > 0 && i < len {
arr[index].append(charArr[i])
i += 1
index -= 1
}
}
var res = String()
for i in 0..<numRows {
res += (arr[i])
}
return res
}
}
Amazing Answer
-Build numRows array
-Append character to the corresponding array
- Append array
网友评论