Describe:
The string is "PAYPALISHIRING" written with a zigzag pattern on a given number of rows like this: (You could 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 would take a string and make this conversion given a number of rows:
String convert (string text, int nRows);
convert("PAYPALISHIRING", 3) should return "Pahnaplsiigyir" .
observed
| 0 |
|
|
|
8 |
| |
|
7 |
9 |
| 2 |
|
6 |
|
10 |
| 3 |
5 |
|
|
11 |
| 4 | TD class= "XL65" >
|
|
12 |
to deal with two parts, a line 0-1-2-3-4 and a slash of 5-6-7, followed by a repetition of these two, creating a string arrayAns=new String[nrows] Save each line of letters, then two loops, one for loop processing line, one handle slash
For (J=0;i<s.length () &&j<nrows;j++) {
Ans[j]+=s.charat (i);
i++;
}
For (J=nrows-2;j>0&&i<s.length (); j--) {
Ans[j]+=s.charat (i);
i++;
}
I represents the subscript of the original string, and when I reaches the end of the loop, this method is simple and easy to understand, and the time complexity O (n).
1 PublicString Convert (String s,intnRows) {2 if(S.length () <=nrows| | Nrows==1)//Special Case Processing3 returns;4 intI=0,j=0;5 intNrows_minus_ends=nrows-2;6String[] Ans=NewString[nrows];7 for(intk=0;k<ans.length;k++)8Ans[k]= "";9 while(i<s.length ()) {Ten for(J=0;i<s.length () &&j<nrows;j++){ Oneans[j]+=S.charat (i); Ai++; - } - for(J=nrows_minus_ends;j>0&&i<s.length (); j--){ theans[j]+=S.charat (i); -i++; - } - } +String ansstring= ""; - for(intk=0;k<ans.length;k++) +ansstring+=Ans[k]; A returnansstring; at}View Java Code
LeetCode6 ZigZag Conversion