ACM题库~

LeetCode 6. ZigZag Conversion

2017-09-08  本文已影响18人  关玮琳linSir

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;
    }
};

上一篇下一篇

猜你喜欢

热点阅读