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 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
solution 1
這道題比較簡單,規(guī)律比較明顯。
下圖中的方格表示字符轰驳,數(shù)字表示字符在字符串中的下標(biāo)徊都。
可以看到每行的數(shù)字都是有規(guī)律的叉橱。
show code
public String convert(String s, int numRows) {
if (numRows <= 1) {
return new String(s);
}
int len = s.length();
int step = (numRows - 1) << 1;
char[] cs = new char[len];
for (int i = 0, j = 0; i < numRows; i++) {
int index = i;
while(index < len) {
cs[j++] = s.charAt(index);
index += step;
if (index % (numRows - 1) != 0 && index - (i << 1) < len) {
cs[j++] = s.charAt(index - (i << 1));
}
}
}
return new String(cs);
}
時間復(fù)雜度:挟鸠,每個元素只會訪問一次童太。
空間復(fù)雜度:。
提交代碼