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 RAnd 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 text, int nRows);
convert("PAYPALISHIRING", 3)
should return"PAHNAPLSIIGYIR"
.Difficulty: Easy
最直接的遍历:272ms
1 public string Convert(string s, int numRows) { 2 if (numRows < 2||s.Length<3||s.Length<=numRows) return s; 3 4 List<char> list=new List<char>(); 5 int temp = 2*numRows - 2; 6 for (int j = 1; j <= numRows; j++) 7 { 8 for (int i = 1; i <= s.Length; i++) 9 { 10 int y = i%temp; 11 if (y == j || numRows - (y - numRows) == j || (y==0&&j==2)) list.Add(s[i - 1]); 12 } 13 } 14 15 return new string(list.ToArray()); 16 }
很直接的遍历:188ms
1 public string Convert(string s, int numRows) { 2 int len = s.Length; 3 if (numRows < 2||s.Length<3||len<=numRows) return s; 4 5 StringBuilder[] sb=new StringBuilder[numRows]; 6 for (int i = 0; i < sb.Length; i++) 7 { 8 sb[i]=new StringBuilder(); 9 } 10 11 int j = 0; 12 while (j < len) 13 { 14 for (int n = 0; n < numRows && j < len; n++) 15 { 16 sb[n].Append(s[j++]); 17 } 18 for (int n = numRows - 2; n >= 1 && j < len; n--) 19 { 20 sb[n].Append(s[j++]); 21 } 22 } 23 24 for (int i = 1; i < sb.Length; i++) 25 { 26 sb[0].Append(sb[i]); 27 } 28 return sb[0].ToString(); 29 }