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

链接: http://leetcode.com/problems/zigzag-conversion/

题解: 

根据例子列出n = 3和n = 4的情况,计算出列间距zigSize = 2 * numRows - 2,所以每行元素为 i + n * zigSize以及斜线的计算公式,当i为行数时,斜线上元素为i + n * zigSize - 2 * i。

Time Complexity - O(n), Space Complexity - O(n)。

public class Solution {

    public String convert(String s, int numRows) {

        int zigSize = 2 * numRows - 2;

        if(s == null || s.length() == 0 || zigSize <= 0)

            return s;

        StringBuilder result = new StringBuilder();

        

        for(int i = 0; i < numRows; i ++){

            for(int j = i; j < s.length(); j += zigSize){

                result.append(s.charAt(j));    

                if(i != 0 && i != numRows - 1 && j + zigSize - 2 * i < s.length() )

                    result.append(s.charAt(j + zigSize - 2 * i));

            }

        }

        

        return result.toString();

    }

}

 

测试:

Reference:

http://www.cnblogs.com/springfor/p/3889414.html

 

你可能感兴趣的:(conversion)