My Leetcode journey, this chapter mainly completes the use of Java implementation algorithm. This is the 6th article zigzag Conversion
All code Download: GitHub Link: GitHub link, click Surprise, write article is not easy, welcome everyone to take my article, and give useful comments, of course you can also pay attention to my GitHub;
1. Topic Description:
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"
.
2. My train of thought:
1. You can write the number of 5 lines with the pen zigzag and then look for the law
2. We can see that the law follows a pattern in addition to the first and last lines:
All from: i,i+ (numrows-1-i) *2,i+ (numrows-1-i) *2+2*i;
3. Use StringBuilder for iterative additions
3. My AC Code
Package com.rlovep.string;/** * ZigZag Conversion * My idea: * 1. You can write the number of 5 lines with the pen ZigZag and then look for the pattern * 2. From what we can see, the law follows a pattern in addition to the first and last lines: * All from: i,i+ (numrows-1-i) *2,i+ (numrows-1-i) *2+2*i; * 3. Use StringBuilder to iterate add * * @author peace * * * Public class ZigZag { PublicString Convert (String s,intNumRows) {if(s==NULL||"". Equals (s) | | numrows==1)returnS StringBuilder sb=NewStringBuilder ();int Index=0;intLength=s.length ();intL1= (numrows-1) <<1; while(true){if(Index<length) {Sb.append (S.charat (Index));Index+=L1; }Else{ Break; } } for(intI=1; i<numrows-1; i++) {l1= (numrows-1-i) <<1;intl2=i<<1;Index=i; while(true){if(Index<length) {Sb.append (S.charat (Index));Index+=L1; }Else{ Break; }if(Index<length) {Sb.append (S.charat (Index));Index+=L2; }Else{ Break; } } }Index=numrows-1; L1= (numrows-1) <<1; while(true){if(Index<length) {Sb.append (S.charat (Index));Index+=L1; }Else{ Break; } }returnSb.tostring (); }}
Ok this chapter is introduced here from the Wpeace (blog.wpeace.cn)
Java version of Leetcode06-zigzag conversion