Tuesday, March 18, 2014

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

n=4
P              I              N
A         L  S         I   G
Y   A       H    R
P              I

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

The key points of this problem is to get the fact that:
  • zigSize=2nRows-2
  • In each zig, the index of the next element in between (in green) is index + (nRows-i-1)*2. For example, whenRow = 5, the current row=3, index(L) = index(P) + (5-3-1)*2=3+2=5;

class Solution {
public:
string convert(string s, int nRows) {
if(s.size()<=0) return s;
if(nRows<=1) return s;
string ret;
for(int i=0; i<nRows; i++){
for(int j=0, index=i; index<s.size(); j++, index = (2*nRows-2)*j+i){
ret.append(1, s[index]);
if(i==0 || i==nRows-1) continue;
index = index + (nRows-i-1)*2;
if(index<s.size())
ret.append(1, s[index]);
}
}
return ret;
}
};
view raw gistfile1.java hosted with ❤ by GitHub

No comments:

Post a Comment