题目
leetcode6. Z字形变换
将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 “LEETCODEISHIRING” 行数为 3 时,排列如下(为显示整齐增加-):
L----------C-----------I---------R
E----T----O----E----S----I----I----G
E----------D----------H--------N
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“LCIRETOESIIGEDHN”。
请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
示例 1:
输入: s = “LEETCODEISHIRING”, numRows = 3
输出: “LCIRETOESIIGEDHN”
示例 2:
输入: s = “LEETCODEISHIRING”, numRows = 4
输出: “LDREOEIIECIHNTSG”
代码
- 思路
- 若 numRows <= 0, 直接返回空string;
- 若 numRows == 1, 直接返回 s;
- 若 numRows >= 2, 能发现其实对每个 “对勾√”形的一组元素(例如 numRows == 3时每4个元素, 每组元素数= 2 * numRows - 2)处理逻辑相同;
- 创建具有 numRows 个元素的字符串 vector temp_vc, 每个字符串存储一行元素;
- 对于每组 2 * numRows - 2 个元素,假设 某元素在原字符串 s 中的下表为 i, 则有:
- 假设该元素是组中的第 index 个 元素,则有 index = i % (numRows * 2 - 2);进一步分析:
- index < numRows ( “对勾√”形中的 |)时,temp_vc[index] += s[i];
- index >= numRows ( “对勾√”形中的 /)时, temp_vc[2 * (numRows - 1) - index] += s[i];
- 假设该元素是组中的第 index 个 元素,则有 index = i % (numRows * 2 - 2);进一步分析:
- 最后将 temp_vc 中的字符串串联起来为最终结果。
- 代码
#include <string>
#include <vector>
using namespace std;
// char* convert(char* s, int numRows) {}
class Solution {
public:
string convert(string s, int numRows) {
if (numRows <= 0) {
return string();
} else if (1 == numRows) {
return s;
} else {
string res;
vector<string> temp_vc(numRows);
for (int i = 0; i < s.size(); ++i) {
int index = i % (numRows * 2 - 2);
if (index < numRows) {
temp_vc[index] += s[i];
} else {
temp_vc[2 * (numRows - 1) - index] += s[i];
}
}
for (auto& str : temp_vc) {
res += str;
}
return res;
}
}
};
测试
#include <iostream>
int main() {
Solution s;
string str = "LEETCODEISHIRING";
cout << s.convert(str, 3);
cin.get();
return 0;
}
- 结果
LCIRETOESIIGEDHN