LeetCode算法题之第6题ZigZag Conversion

2016-08-04  本文已影响39人  浩水一方

Question:

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

解决:

输出为Z形状的字符串。

public String convert(String s, int numRows) {
    int temp = 2 * numRows - 2;
    String result[] = new String[numRows];
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < numRows; ++i){
        result[i] = "";
    }
    for (int i = 0; i < s.length(); ++i){
        if (temp != 0)
            result[i%temp >= numRows ? temp-i%temp:i%temp] += s.charAt(i);
        else
            result[temp] += s.charAt(i);
    }
    for (int i = 0; i < result.length; ++i){
        sb.append(result[i]);
    }
    return sb.toString();
}

代码地址(附测试代码):
https://github.com/shichaohao/LeetCodeUsingJava/tree/master/src/zigZagConversion

上一篇下一篇

猜你喜欢

热点阅读