题目描述:将一个给定字符串s根据给定的行数numRows,从上往下、从左到右进行Z字形排列
示例:
输入:s = "PAYPALISHIRING", numRows = 4 输出:"PINALSIGYAHRPI" 解释: P I N A L S I G Y A H R P I 输入:s = "A", numRows = 1 输出:"A"
思路:
用vectornewStr,字符串数组作为新数组,遍历s,加到对应行的字符串后面。 遍历思路:根据up(路线方向)看current是++还是--,如果current到最上或最下了,up转向
代码+解析:
class Solution {
public:
string convert(string s, int numRows) {
int len = s.size();
if(len == 1 || numRows == 1 || len <= numRows){ //只有1个的情况
return s;
}
vector newStr(numRows);
int current = 0; //当前行
int up = 0; //up=0表示向下,up=1表示向上
for(char c : s){
newStr[current] += c; //加到字符串上
current = up ? current-1 : current+1; //如果是up,x--,否则x++
if(current == numRows-1 || current == 0){
up = !up; //箭头反转
}
}
string str;
for(string row : newStr){
str += row;
}
return str;
}
};
学到的总结:
-
vector : 不要用vector
!!!,string更好! -
三元表达式:condition ? expression1 : expression2;
if (condition){ cur = a; }else { cur = b; } ==> cur = condition ? a : b -
遍历:char c : s



