[Problem]
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"
.
[Analysis]
这题比较简单,大概有两类思路:一是找到规律按一定的间隔直接将字符存入buffer,二是分开每行分别建立字符串最后将所有字符串连接起来。前者规律要稍微复杂一点,但内存方面稍微优化。一开始我采用的是将例子写在纸上找规律的暴力方法,只要将规律列清楚,一样可以求解。
[Solution]
public class Solution { public String convert(String s, int nRows) { if (s.length() <= nRows || nRows == 1) { return s; } StringBuffer buf = new StringBuffer(""); for (int i = 0; i < nRows; i++) { int interval1 = (nRows - i - 1) * 2; int interval2 = i * 2; if (interval2 == 0 || interval1 == interval2) { for (int j = i; j < s.length(); j += interval1) { buf.append(s.charAt(j)); } } else if (interval1 == 0) { for (int j = i; j < s.length(); j += interval2) { buf.append(s.charAt(j)); } } else { buf.append(s.charAt(i)); for (int j = i + interval1; j < s.length(); j += interval1) { buf.append(s.charAt(j)); j += interval2; if (j < s.length()) { buf.append(s.charAt(j)); } } } } return buf.toString(); } }
时间: 2024-10-07 03:53:39