(字符串)ZigZag Conversion
Posted Kobe10
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了(字符串)ZigZag Conversion相关的知识,希望对你有一定的参考价值。
【解析】
第一次看到这个题目的人,可能不知道ZigZag是什么意思,简单解释一下,就是把字符串原顺序012345……按下图所示排列:
发现所有行的重复周期都是 2 * nRows - 2
对于首行和末行之间的行,还会额外重复一次,重复的这一次距离本周期起始字符的距离是 2 * nRows - 2 - 2 * i
- class Solution {
- public:
- string convert(string s, int nRows) {
- // Start typing your C/C++ solution below
- // DO NOT write int main() function
- string result;
- if (nRows < 2) return s;
- for (int i = 0;i < nRows;++i) {
- for (int j = i;j < s.length();j += 2 * (nRows - 1)) {
- result.push_back(s[j]);
- if (i > 0 && i < nRows - 1) {
- if (j + 2 * (nRows - i - 1) < s.length())
- result.push_back(s[j + 2 * (nRows - i - 1)]);
- }
- }
- }
- return result;
- }
- };
以上是关于(字符串)ZigZag Conversion的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 6. ZigZag Converesion 之字型转换字符串