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

public class Solution {

    public String convert(String s, int nRows) {

        if(nRows <= 1) return s;

        String result = "";
        int sizeString = s.length();
        int zigSize = nRows* 2 - 2;
        for(int i = 0; i < nRows; i ++){
            for(int base = i; ; base += zigSize){
                if(base >= sizeString)
                    break;
                result += s.charAt(base);

                if(i >0 && i < nRows-1 && (base + zigSize - 2* i) < sizeString){
                    result += s.charAt(base + zigSize - 2* i);
                }
            }
        }

        return result;
    }


    public static void main(String[] args) {
        Solution s = new Solution();
        String str = s.convert("123456789", 4);
        System.out.println(str);
    }
}

results matching ""

    No results matching ""