题目
将一个给定字符串 s
根据给定的行数 numRows
,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 "PAYPALISHIRING"
行数为 3
时,排列如下:
P A H N A P L S I I G Y I R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"PAHNAPLSIIGYIR"
。
示例
输入:s = "PAYPALISHIRING", numRows = 3 输出:"PAHNAPLSIIGYIR"
输入:s = "A", numRows = 1 输出:"A"
解题思想
建立一个字符串数组,数组中字符串的个数为给定的行数numRows
。对给定的字符串从头到尾进行遍历,按照一定的次序和方向将遇到的字符 放在字符串数组中对应的字符串当中。设置一个布尔变量flag,表示存放到字符串数组的方向。设置一个从0到numRows-1
之间变化的整形变量index,每安放一个字符,index的数值就减一,当index的数值变为0时,flag值变为true,表示接下来应该向下走;当index的数值变为numRows-1
时,flag值变为false,表示接下来应该向上走。
代码实现
class Solution {
public:
string convert(string s, int numRows) {
int size = s.size();
int storeSize = min(size,numRows);
vector<string> data(numRows);
if(numRows == 1) return s;
int index = 0;
bool flag = false;
for(int i = 0;i < s.size();i ++){
data[index].push_back(s[i]);
if(index == 0)
flag = true;
if(index == storeSize-1)
flag = false;
if(flag == true)
index ++;
else
index --;
}
string result;
for(int i = 0;i < storeSize;i ++){
result += data[i];
}
return result;
}
};