水题。主要就是画画图,找找规律。稍微要注意的是:1. nRow为1的情况;2. 采用变量index方便边界判断
public class Solution {
public String convert(String s, int nRows) {
StringBuilder sb = new StringBuilder();
if (nRows == 1) return s;
// nRows >= 2
for (int i = 0; i * (2 * nRows - 2) < s.length(); i++)
{
sb.append(s.charAt(i * (2 * nRows - 2)));
}
for (int i = 1; i < nRows - 1; i++)
{
for (int j = 0;; j++)
{
int index = j * (2 * nRows - 2) - i;
if ( index > 0 && index < s.length())
{
sb.append(s.charAt(index));
}
index = j * (2 * nRows - 2) + i;
if ( index > 0 && index < s.length())
{
sb.append(s.charAt(index));
}
else
{
break;
}
}
}
// last
if (nRows != 0 && nRows != 1)
{
for (int i = 0; i * (2 * nRows - 2) + nRows - 1 < s.length(); i++)
{
sb.append(s.charAt(i * (2 * nRows - 2) + nRows - 1));
}
}
return sb.toString();
}
}
第二刷,先找规律,写公式,然后写代码,要注意行数为1的情况:
class Solution {
public:
string convert(string s, int nRows) {
if (nRows == 1) return s;
string res;
int inc = (nRows - 1) * 2;
for (int i = 0; i < nRows; i++)
{
for (int j = i; j < s.length(); j += inc)
{
res.push_back(s[j]);
if (i == 0 || i == nRows - 1)
continue;
if (j + inc - i * 2 < s.length())
res.push_back(s[j + inc - i * 2]);
}
}
return res;
}
};