6.[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)app

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:this

string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".code

Analysis & Solution

There exits pattern in the ZigZag Conversion. The indexs at i row follows patterns:string

Let DiffConstant = 2*row - 2it

i = 0: the difference = DiffConstantio

i = 1: the differences = 2(row-1) - 2, DiffConstant - (2(row-1) - 2).di

i = 2: the differences = 2(row-2) - 2, DiffConstant - (2(row-2) - 2).ant

i = k: the differences = 2(row-k) - 2, DiffConstant - (2(row-k) - 2) = 2kmake

public String convert(String s, int numRows) {
        if(numRows == 1){
            return s;
        }
        int diffConstant = 2*numRows - 2, i, index;
        StringBuffer res = new StringBuffer();
        for(i = 0; i < numRows; i++){
            index = i;
            boolean isEven = true;
            while(index < s.length()){
                res.append(s.charAt(index));
                if(i == 0 || i == numRows -1){
                    index += diffConstant; 
                }else{
                    if(isEven){
                        index += 2*(numRows-i) - 2;
                    }else{
                        index +=  2*i;
                    }
                    isEven = !isEven;
                }
            }
        }
        return res.toString();
    }
相關文章
相關標籤/搜索