LeetCode 解题报告 - 6. ZigZag Conver

2016-10-11  本文已影响0人  秋名山菜车手

对 hard 类型的题,表示目前实在是 hold 不住,暂时先不刷啊。等我刷完 easy 和 medium 回头再战! 2016/10/10
编程语言是 Java,代码托管在我的 GitHub 上,包括测试用例。欢迎各种批评指正!

<br />

题目 —— ZigZag Conversion

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of row 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".
<br >

解答

public class Solution {
    public String convert(String s, int numRows) {
        StringBuilder[] sb = new StringBuilder[numRows];
        for (int i = 0; i < numRows; i++) {
            sb[i] = new StringBuilder();
        }
        int i = 0;
        while (i < s.length()) {
            for (int rowIndex = 0; rowIndex < numRows && i < s.length(); rowIndex++) {
                sb[rowIndex].append(s.charAt(i++));
            }
            for (int rowIndex = numRows - 2; rowIndex > 0 && i < s.length(); rowIndex--) {
                sb[rowIndex].append(s.charAt(i++));
            }
        }
        for (i = 1; i < numRows; i++) {
            sb[0].append(sb[i]);
        }
        return sb[0].toString();
    }
}
上一篇下一篇

猜你喜欢

热点阅读