Skip to content

Instantly share code, notes, and snippets.

@spurscho
Created December 20, 2019 23:26
Show Gist options
  • Save spurscho/ba3f32e42f0e43aae04c81a2d1c19182 to your computer and use it in GitHub Desktop.
Save spurscho/ba3f32e42f0e43aae04c81a2d1c19182 to your computer and use it in GitHub Desktop.
6. ZigZag Conversion
class Solution {
func convert(_ s: String, _ numRows: Int) -> String {
var groups = [[String]](repeating: Array(repeating: " ", count: s.count), count: numRows)
var idx = 0
var v = 0
var h = 0
var str = ""
var resStr = ""
if numRows == 0 {
return ""
}
if s.count <= numRows || numRows == 1 {
return s
}
while idx < s.count {
str = String(s[s.index(s.startIndex, offsetBy: idx)])
groups[v][h] = str
if v == numRows-1 {
while v > 0 {
h += 1
v -= 1
idx += 1
str = String(s[s.index(s.startIndex, offsetBy: idx)])
groups[v][h] = str
}
}
v += 1
idx += 1
}
var tempStr = ""
for i in 0 ..< numRows {
for j in 0 ..< s.count {
tempStr = groups[i][j]
resStr += tempStr.filter({ $0 != " "})
}
}
return resStr
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment