标签:
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 text, int nRows);
convert("PAYPALISHIRING", 3)
should return "PAHNAPLSIIGYIR"
.
分析:https://segmentfault.com/a/1190000005751185
打印题,二话不说,画图,标数字,找规律。
这题其实是EPI这本书里7.11题(Write a string sinusoidally),书里的题规定k=3,在leetcode里k作为参数,所以更难了。
leetcode的这个例子的图非常反人类,其实可以把它画得优美一些,像正弦函数的波浪形:
P A H N
A P L S I I G
Y I R
举个别的例子自己画一下:
经观察发现,对于每个nRows(为了简便用k表示),都有一个自己的magic number = 2 * k - 2
1 public class Solution { 2 public String convert(String s, int nRows) { 3 if (s == null || s.length() <= nRows || nRows <= 1) return s; 4 StringBuffer sb = new StringBuffer(); 5 // the first row 6 for (int i = 0; i < s.length(); i += (nRows - 1) * 2) { 7 sb.append(s.charAt(i)); 8 } 9 10 for (int i = 1; i < nRows - 1; i++) { 11 for (int j = i; j < s.length(); j+= (nRows - 1) * 2) { 12 sb.append(s.charAt(j)); 13 if (j + (nRows - i - 1) * 2 < s.length()) { 14 sb.append(s.charAt(j + (nRows - i - 1) * 2)); 15 } 16 } 17 } 18 // the last row 19 for (int i = nRows - 1; i < s.length(); i += (nRows - 1) * 2) { 20 sb.append(s.charAt(i)); 21 } 22 return sb.toString(); 23 } 24 }
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5740742.html