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 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
Example 3:
Input: s = "A", numRows = 1
Output: "A"
Constraints:
1 <= s.length <= 1000
s consists of English letters (lower-case and upper-case), ',' and '.'.
1 <= numRows <= 1000
z字型,新的字符串每行字符,每个字符对应左列开头字符以间隔 interval=2numRows-2 。每行每个周期会有2个字符不断以 interval 输出,第一行和最后一行比较特殊,每个周期只有1个。
class Solution {
public String convert(String s, int numRows) {
if(numRows==1) return s;
int len=s.length();
char[] c=new char[len];
int interval=2*numRows-2;
int index=0;
int i1=0,i2;
while(i1<len){
c[index++]=s.charAt(i1);
i1+=interval;
}
for(int i=1;i<numRows-1;++i){
i1=i;
i2=2*numRows-2-i1;
while(true){
if(i1>=len) break;
c[index++]=s.charAt(i1);
i1+=interval;
if(i2>=len) break;
c[index++]=s.charAt(i2);
i2+=interval;
}
}
i1=numRows-1;
while(i1<len){
c[index++]=s.charAt(i1);
i1+=interval;
}
return String.valueOf(c);
}
}