leetcode-6. ZigZag Conversion

xiaoxiao2021-09-17  28

leetcode-6. ZigZag Conversion

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”.

我的解法

public class Solution { public String convert(String s, int numRows) { if(numRows < 2) return s; StringBuilder[] sbl = new StringBuilder[numRows]; for(int i = 0 ; i < sbl.length ; i++) sbl[i] = new StringBuilder(); boolean flag = true; for(int i = 0,j = 0 ; i < s.length() ;){ if(flag) sbl[j++].append(s.charAt(i++)); else sbl[j--].append(s.charAt(i++)); if(j == numRows-1 || j == 0) flag = !flag; } String ret = ""; for(StringBuilder sb : sbl) ret += sb; return ret; } }

用一个StringBuilder，然后指针计数的方法。

public String convert(String s, int numRows) { if(numRows < 2 || numRows >= s.length()) return s; StringBuilder sb = new StringBuilder(s.length()); int origStep = numRows * 2 - 2; int step = origStep; for(int i = 0; i < numRows; i++){ step = i == numRows - 1 ? origStep : origStep - i * 2; int curr = i; while(curr < s.length()){ sb.append(s.charAt(curr)); curr += step; int temp = Math.abs(step - origStep); step = temp == 0 ? origStep : temp; //First/last rows } } return sb.toString(); }