Leetcode_6_ZigZag Conversion, leetcode_6_zigzag
Description:
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 NA P L S I I GY 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)Shocould return
"PAHNAPLSIIGYIR".
Ideas:
After thinking for a long time, thinking is always limited to two-dimensional arrays, looking for a certain relationship between the length of the string and the number of rows and columns of two-dimensional arrays, thinking for a long time, no idea.
Then I went online and looked at it. There was a way of saying that I could use a string array. I thought of StringBuilder. How good is direct Append? How advanced is it than a two-dimensional array! Then we use StringBuilder to solve this problem.
Code:
public String convert(String s, int nRows) { if(s==null) return null; else if (s.equals("")) return ""; int len=s.length(); StringBuilder resultBuilder=new StringBuilder(); StringBuilder []sBuilder=new StringBuilder[nRows]; for(int i=0;i<nRows;i++) sBuilder[i]=new StringBuilder(); int i=0,j=0; while(i<len) { for(j=0;j<nRows;j++) { if(i==len) break; sBuilder[j].append(s.charAt(i)); i++; } for(j=nRows-2;j>=1;j--) { if(i==len) break; sBuilder[j].append(s.charAt(i)); i++; } } for(i=0;i<nRows;i++) resultBuilder.append(sBuilder[i]); return resultBuilder.toString(); }
Result: