leetcode 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 s, int numRows);
Example 1:

Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”
Example 2:

Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
Explanation:

P I N
A L S I G
Y A H R
P I

很简单,设置 nnstring ,然后设置一个步长 t,当添到 0 行时,步长 t 置为 1,添到 n-1 行时,步长 t 置为 -1,然后行坐标加上步长。复杂度 O(n)O(n)

class Solution {
public:
    string convert(string s, int numRows) {
        if(numRows==1)return s;
        vector<string> res(numRows,"");
        int n=s.length(),k=0,t=1;
        for(int i=0;i<n;i++){
            res[k]+=s[i];
            if(k==numRows-1)t=-1;
            if(k==0)t=1;
            k+=t;
        }
        string r="";
        for(int i=0;i<numRows;i++)
            r+=res[i];
        return r;
    }
};
posted @ 2020-05-07 22:20  winechord  阅读(59)  评论(0编辑  收藏  举报