这道题其实有两个思路
思路一:按顺序把每个字母分配到对应的行,再把行联接起来。具体是用一个string array来代表每一行,用一个current_row来记住现在的行数,然后用go记住方向,向下就是+1,向上就是-1,这样可以不停的运算更新current_row, 在顶行和底行反转go。
class Solution: def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ if len(s) == 0 or numRows <= 1: return s row_list = ["" for x in range(numRows)] current_row = 0 go = -1 for c in s: row_list[current_row] += c if (current_row == 0 or current_row == numRows-1): go = -go current_row += go rst = "" for row in row_list: rst += row return rst
思路二:就是直接算出下一个字母是哪一个。size是numRows-2,between就是numRows+size = 2*numRows-2
class Solution { public String convert(String s, int numRows) { if (numRows <= 1) { return s; } StringBuilder rst = new StringBuilder(); int size = 2 * numRows - 2; for (int i = 0; i < numRows; i++) { for (int j = i; j < s.length(); j += size) { rst.append(s.charAt(j)); int between = j + size - 2 * i; if(i != 0 && i != numRows - 1 && between < s.length()){//except the first row and the last row rst.append(s.charAt(between)); } } } return rst.toString(); } }
个人觉得其实第二个方法比较不好像,第一个方法反而比较直观。