LeetCode 6. ZigZag Conversion

6. ZigZag Conversion

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:

string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

这个题的意思就是我们要把字符串按照锯齿形来排列,然后按行组合在一起输出。

c++:

class Solution {
public:
    std::string convert(std::string s, int nRows) {
        if(nRows==1)return s;
        int l=s.size();
        int r=0,t=1;
        std::string *ss = new std::string[nRows];
        for(int i=0;i<l;i++){
            ss[r].push_back(s[i]);
            if(r==0)t=1;
            else if(r==nRows-1)t=-1;
            r+=t;
        }
        std::string sss="";
        for(int i=0;i<nRows;i++){
            sss.append(ss[i]);
        }
        delete[] ss;
        return sss;
    }
};

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容