题目简介
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"
.
自己的解法
= =道题刚开始的时候根本没看明白,题目的意思。= =没办法只能从网上找了一下别人的说明,才看明白了这道题目。自己对于Java的字符串处理有点不太懂(因为不像C那样可以直接用下标处理)= =所以直接看了hot解法
Hot解法
- public class Solution {
public String convert(String s, int numRows) {
int nRows = numRows;
char[] c = s.toCharArray();
int len = c.length;
StringBuffer[] sb = new StringBuffer[nRows];
for (int i = 0; i < sb.length; i++) sb[i] = new StringBuffer();
int i = 0;
while (i < len) {
for (int idx = 0; idx < nRows && i < len; idx++) // vertically down
sb[idx].append(c[i++]);
for (int idx = nRows-2; idx >= 1 && i < len; idx--) // obliquely up
sb[idx].append(c[i++]);
}
for (int idx = 1; idx < sb.length; idx++)
sb[0].append(sb[idx]);
return sb[0].toString();
}
}
感受
其实看懂了这道题目,Hot解法的代码不是很难理解。通过这次的hot解法,在Java中每次我有解题的思路时,但想到不能用下标访问,我就只能去通过Java本身的一些字符串函数来处理。有些问题用本身有的函数可能没有那么好处理。这次我学会了toCharArray()这个函数,可以把字符串转换成字符数组来进行操作。最近被LeetCode虐的有点惨,不是没什么思路,就是始终无法AC。所以决定先从简单的通过率高的题目开始做起。