leetcode(4)
阿新 • • 發佈:2019-01-14
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 s, int numRows);
Example 1:
Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”
Example 2:
Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
Explanation:
P I N
A L S I G
Y A H R
P I
和很多人一樣,剛看題目並不知道說的是什麼。
其實這道題就是要根據鋸齒狀遍歷一個字串
思路簡單直接根據規律遍歷就行了;
public String convert(String s, int numRows) { StringBuilder[] str = new StringBuilder[numRows]; for(int i = 0 ; i < str.length ; i++) { str[i] = new StringBuilder(); } int i = 0; char[] c = s.toCharArray(); int len = c.length; while(i < len) { for(int index = 0 ; index < numRows && i < len; index ++)//直接向下遍歷 { str[index].append(c[i]); i++; } for(int index = numRows - 2; index >= 1 && i < len; index--)//向上遍歷 { str[index].append(c[i]); i++; } } for(int index = 1 ; index < str.length; index++)//連起來 { str[0].append(str[index]); } return str[0].toString(); }