题目:
我的解法(c++)
class Solution {
public:
string convert(string s, int numRows) {
int length = s.length();
string result = "";
if (length < 1) return "";
if (numRows >= length || numRows==1) return s;
int pos1=0, pos2 = 0,row=0,i=0;
int col = length / (2 * numRows - 2)+1;
while (row < numRows)
{
for (i=0;i<col;i++)
{
int tmp = 2 * numRows - 2 - row;
pos1 = i*(2 * numRows - 2)+row;
pos2 = tmp +i* (2 * numRows - 2);
if (pos1 > s.length()-1) break;
if (row == 0 || row ==numRows-1)
{
result.append(s, pos1, 1);
}
else {
result.append(s, pos1, 1);
if (pos2 > length - 1) break;
result.append(s, pos2, 1);
}
}
row++;
}
return result;
}
};
结果:
官方答案:
class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1) return s;
vector<string> rows(min(numRows, int(s.size())));
int curRow = 0;
bool goingDown = false;
for (char c : s) {
rows[curRow] += c;
if (curRow == 0 || curRow == numRows - 1) goingDown = !goingDown;
curRow += goingDown ? 1 : -1;
}
string ret;
for (string row : rows) ret += row;
return ret;
}
};
结果:
补充知识点1
今天博主还是感觉很有收获的,第一次发现原来C++中**for循环和+**还能如此用法:
eg1.
for (char c : s)//遍历字符串S,其中以char类型进行遍历
rows[curRow] += c;
等价于:
for(int i=0;i<s.length();i++)
{
char c=s[i];
}
eg2.
for (string row : rows) //遍历vector,其中以string类型进行遍历
ret += row;
神奇之处来了:
这两个例子中,字符串的连接均是采用了+号!!!既可以通过加号实现字符串的扩充,可以一个字符一个字符地加,也可以一个字符串一个字符串地加,博主惊了!!那还用什么append()函数呢…
此处博主特意查了一下,发现原来标准库中早已经重载了+号运算符:
basic_string& operator+=(const basic_string& _Right)
{ // append _Right
return (append(_Right));
}
补充知识点2
博主记性不好,每次都忘了向量总共有哪些初始化类型来的了,特意在此做下笔记:
一维向量的初始化:
vector<int> a; //声明一个int型向量a
vector<int> a(10); //声明一个初始大小为10的向量
vector<int> a(10, 1); //声明一个初始大小为10且初始值都为1的向量
vector<int> b(a); //声明并用向量a初始化向量b
vector<int> b(a.begin(), a.begin()+3);//将a向量中从第0个到第2个(共3个)作为向量b的初始值
具体使用方法可以查看:https://blog.csdn.net/qq_36427732/article/details/79652430