The string is "PAYPALISHIRING" written with 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 on 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" .
Positioning: Medium problem
Test instructions better understand, will give the string Z-type, re-read, you can find that each character appears in a regular position, for the N-height of the z-type, the characters appearing in the same position in Z/((n-1)/2) The remainder is the same, regardless of n=1, if the new string is the same as the original string.
The Java implementation is as follows:
1 Public classSolution {2 PublicString Convert (String s,intnumrows) {3 intlen=s.length ();4 if(numrows==1){5 returns;6 }7 intGay=numrows*2-2;8StringBuffer stringbuffer=NewStringBuffer ();9 intj,h;TenJ=0; One while(j<Len) { A Stringbuffer.append (S.charat (j)); -j+=Gay; - } the for(inti=1;i<gay/2;i++){ -j=i; -h=gay-i; - while(j<Len) { + Stringbuffer.append (S.charat (j)); -j+=Gay; + if(h<Len) { A Stringbuffer.append (S.charat (h)); ath+=Gay; - } - } - } -J=numrows-1; - while(j<Len) { in Stringbuffer.append (S.charat (j)); -j+=Gay; to } + returnstringbuffer.tostring (); - } the}
Leetcode 006 ZigZag Conversion-java