Friday, January 17, 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".

We add another example to clarify, same string with 4 rows
P     I     N
A   L S   I G
Y A   H R   
P     I 
convert("PAYPALISHIRING", 4) should return "PINALSHIGYAHRPI"

Solution:

public class Solution {
    public String convert(String s, int nRows) {
        if(nRows==1)
            return s;
        int step1 = 2*(nRows-1);
        int step2 = 0;
        StringBuilder sb = new StringBuilder();
        for(int i=0; i<nRows; i++)
        {
            int pointer = i;
            while (pointer<s.length())
            {
                sb.append(s.charAt(pointer));
                if(step1>0 && step2>0 && pointer+step1<s.length())
                {
                    pointer += step1;
                    sb.append(s.charAt(pointer));
                    pointer += step2;
                }
                else
                    pointer += (step1+step2);
            }
            step1 -=2;
            step2 +=2;
        }
        return sb.toString();
    }
}

No comments :

Post a Comment