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

 

how to init the two dim vector:

Use the std::vector::vector(count, value) constructor that accepts an initial size and a default value:

std::vector<std::vector<int> > fog(
    A_NUMBER,
    std::vector<int>(OTHER_NUMBER)); // Defaults to zero initial value

  

If a value other zero, say 4 for example, was required to be the default then:

std::vector<std::vector<int> > fog(
    A_NUMBER,
    std::vector<int>(OTHER_NUMBER, 4));

  

I should also mention uniform initialization is introduced in C++11, which permits the initialization of vector, and other containers, using {}:

std::vector<std::vector<int> > fog { { 1, 1, 1 },
                                    { 2, 2, 2 } };

  

how to merge two vector:

AB.reserve( A.size() + B.size() ); // preallocate memory
AB.insert( AB.end(), A.begin(), A.end() );
AB.insert( AB.end(), B.begin(), B.end() );

  

 

my code:

class Solution {
public:
    string convert(string s, int numRows) {
        if (numRows == 1) return s;
        int len = s.length();
        vector<vector<char> > v(numRows, vector<char>());
        string ans = "";
        int t = 0, dir = 1;
        for (int i = 0; i < len; ++i) {
            v[t].push_back(s[i]);
            t += dir;
            if (t >= numRows) {
                dir = -1;
                t -= 2;
            }
            if (t < 0) {
                dir = 1;
                t = 1;
            }
        }
        for (int i = 0; i < numRows; ++i) {
            for (int j = 0; j < v[i].size(); ++j) {
                ans += v[i][j];
            }
        }
        return ans;
    }
};

  

Runtime: 24 ms, faster than 56.90% of C++ online submissions for ZigZag Conversion.

 

posted @ 2018-09-28 17:47  Veritas_des_Liberty  阅读(178)  评论(0编辑  收藏  举报