Saturday, May 18, 2013

Day 26, 6, ZigZag Conversion

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".
--------------------------------
Solution #1 use a vector<string>
class Solution {
public:
    string convert(string s, int nRows) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function    
        if (nRows == 1) {
            return s;
        }
        vector<string> ret(nRows); 
        for (int i=0;i<s.length();i++) {
            int row = i%(2*nRows - 2);
            if (row >= nRows) {
                row = 2*nRows - row-2;
            }
            ret[row] += s[i];
        }
        string str = "";
        for (int i=0;i<nRows;i++) {
            str += ret[i];
        }
        return str;
    }
};
Solution #2
class Solution {
public:
    string convert(string s, int numRows) {
        if (numRows == 1) return s;
        string rt = "";
        int zigSize = numRows * 2 - 2;
        for (int row = 0; row < numRows; row++) {
            for (int i = row; i < s.length(); i += zigSize) {
                rt += s[i];
                if (row != 0 && row != numRows - 1) {
                    int mid = i + (numRows - (i % zigSize) - 1) * 2;
                    if (mid < s.length()) {
                        rt += s[mid];
                    }
                }
            }
        }
        
        return rt;
    }
};

No comments:

Post a Comment