[LeetCode][python3]0006. ZigZag Conversion

Start the Journey
N2I -2020.03.15

1. My first try


  1. class Solution:
  2. def convert(self, s: str, numRows: int) -> str:
  3. gap=(numRows-1)*2
  4. if len(s)<2 or gap<=0:
  5. return s
  6. ans=[]
  7. for i in range(numRows):
  8. if i==0 or i==numRows-1:
  9. ans+=s[i::gap]
  10. #print(ans)
  11. else:
  12. dic={}
  13. index=0
  14. for item in s[i::gap]:
  15. dic[index]=item
  16. index+=2
  17. index=1
  18. for item in s[(gap-i)::gap]:
  19. dic[index]=item
  20. index+=2
  21. for index in range(len(dic)):
  22. ans.append(dic[index])
  23. #print(ans)
  24. return ''.join(ans)
  25.  

Explanation:

Just another slow solution.

2. A better solution


  1. class Solution:
  2. def convert(self, s: str, numRows: int) -> str:
  3. #n strings and add them together
  4. listy = [''] * numRows
  5. sign, counter = 1, 0
  6. if numRows == 1:
  7. return s
  8. else:
  9. for i in s:
  10. listy[counter] += i
  11. counter = counter + sign
  12. if counter == numRows - 1:
  13. sign = -1
  14. if counter == 0:
  15. sign = 1
  16. finalStr = ''.join(listy)
  17. return finalStr
  18.  

Explanation:

The solution use a counter to decide which row the i char will be thrown into. And throw all char in string by sequence. It is more simple and faster.