文章目录
leetcode06 [Z字形变换]
题目描述
将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
Example: 输入字符串为 "LEETCODEISHIRING" 行数为 "3" 时,排列如下:
return :
L C I R
E T O E S I I G
E D H N
solution idea
按行排序
通过从左向右迭代字符串,我们可以轻松地确定字符位于 Z 字形图案中的哪一行
class Solution {
public:
string convert(string s, int numRows) {
if (numRows==1) return s;
vector<string> rows(min(numRows, int(s.size())));
int cur_row=0;
bool up_or_down=false;
for (char c : s)
{
rows[cur_row]+=c;
if (cur_row == 0 || cur_row == numRows - 1) up_or_down = !up_or_down;
cur_row+=up_or_down ? 1 : -1;
}
string str_convert;
for (string row : rows)
{
str_convert+=row;
}
return str_convert;
}
};
c++ 语法
STL-string 基本操作
string 表示可变长的字符序列,必须包含string头文件(#include)
初始化和定义对象
string s1 //默认初始化,s1是一个空字符串
string s2=‘hello’ //
string s3=(10,‘a’) // s3=‘aaaaaaaaaa’
string 操作
cctype 头文件函数
Additional Tricks:
STL对象的遍历
扫描二维码关注公众号,回复:
9193983 查看本文章
for (char c : s)//对 string对象s进行遍历
{
rows[cur_row]+=c;
}
<=>
for (int i=0;i<s.size();i++)
{
rows[cur_row]+=s[i];
}
for (string row : rows)//对 vector 对象rows 遍历
{
str_convert+=row;
}
添加字符
+=,append(),push_back()
rows[cur_row]+=c;
str_convert+=row;
参考文献
- c++ prime 第5版
- c++ 标准库
- devdocs
- leetCode—Z 字形变换、for、string、vector笔记
- leetCode—Z 字形变换、for、string、vector笔记