An interesting problem. There are many different solutions, and I prefer the one that easy to understand. The thought is simple: use a parameter 'step' to simulate the process.
Solution:
# T:O(n) S:O(1)
class Solution:
# @param {string} s
# @param {integer} numRows
# @return {string}
def convert(self, s, numRows):
if numRows == 1:
return s
rowN, step, ret = -1, 1, ['' for _ in xrange(numRows)]
for i in xrange(len(s)):
rowN += step
if rowN == numRows:
rowN -= 2
step = -1
elif rowN == -1:
rowN += 2
step = 1
ret[rowN] += s[i]
return ''.join(ret)
Run Time: 112 ms
No comments:
Post a Comment