6. ZigZag Conversion #String (Easy)

Problem:###

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".

Solution:###

The problem statement itself is unclear for many. Especially for 2-row case. "ABCD", 2 --> "ACBD". The confusion most likely is from the character placement. I would like to extend it a little bit to make ZigZag easy understood.
The example can be written as follow:
P.......A........H.......N
..A..P....L..S....I...I....G
....Y.........I........R
Therefore, can be arranged as:
A....C
...B....D

//use a variable step to move from up-down and then down-up.
class Solution {
public:
    string convert(string s, int numRows) {
        if (numRows == 1) return s;
        vector results(numRows,"");
        int row = 0;
        int step = 1;
        for(int i = 0;i < s.length(); i++)
        {
            results[row].push_back(s[i]);
            if(row == 0) step = 1; //move up-down
            if(row == numRows - 1) step = -1; //move down-up
            row += step;
        }
        
        s.clear();
        for(int i = 0;i < results.size();i++)
        {
            s += results[i];
        }
        return s;
    }
};

LeetCode Discussion

你可能感兴趣的:(6. ZigZag Conversion #String (Easy))