LeetCode 6:Z字形变换

题目

这里写图片描述

思路

定义numRows大小的vector容器来存Z字形排列的字符。比对输入输出,忽略空格,可以发现规律,拿出2*numRows-1个字符来看如下图,就是一种迂回读取。先按行升序读取到对应行,然后再反过来降序读取到对应行,一直这样重复即可。
这里写图片描述

注意两种特殊情况:字符串尺寸小于numRowsnumRows=1时,直接返回字符串。

代码

class Solution {
public:
    string convert(string s, int numRows) {
        int n = s.size();
        if(n<numRows||numRows==1)
            return s;
        vector<string> zscan(numRows);
        string result;
        int j=0;
        bool dir = true;
        for(int i=0;i<n;i++)
        {
            zscan[j].push_back(s[i]);
            if(dir)
                j++;
            else
                j--;
            if((j==numRows-1)||(j==0))
                dir = !dir;
        }

        for(int i=0;i<numRows;i++)
            result.insert(result.end(),zscan[i].begin(),zscan[i].end());
        return result;
    }
};

猜你喜欢

转载自blog.csdn.net/lin453701006/article/details/81746196