Monday, September 16, 2013

[Leetcode] 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".


Analysis:

1P

9H

2A
8S
10I
16
3Y
7I
11N
15
4P
6L
12G
14
5A

13


j = nRows*2 -2 if i = 0 || nRows-1, 
j = (nRows-i)*2  if i>0 && i<nRows-1, c is odd

j = i*2 c is even



class Solution {
public:
    string convert(string s, int nRows) {
        
        if(nRows <= 1) return s;
        
        string str;
        for(int i=0; i < nRows; i++)
        {
            int j = i;    
            int c = 0;
            while( j < s.size())
            {
                str.push_back(s[j]);
                c++;
                if (i == 0 || i == nRows - 1)
                    j = j + nRows + nRows - 2;
                else 
                {
                    if (c % 2 == 1)
                        j = j + (nRows-i - 1) * 2;
                    else
                        j = j + i * 2;
                }
            }
        }
        
        return str;
    }
};

No comments:

Post a Comment