Leetcode6 : ZigZag 转换问题

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

原题链接:https://leetcode.com/problems/zigzag-conversion/

Analysis & Solution

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

Let DiffConstant = 2*row - 2

i = 0: the difference = DiffConstant

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

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

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

 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();
    }

原文地址:https://www.cnblogs.com/jun-ma/p/6917202.html