美文网首页
LeetCode算法题之第6题ZigZag Conversion

LeetCode算法题之第6题ZigZag Conversion

作者: 浩水一方 | 来源:发表于2016-08-04 23:02 被阅读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

    相关文章

      网友评论

          本文标题:LeetCode算法题之第6题ZigZag Conversion

          本文链接:https://www.haomeiwen.com/subject/fzufsttx.html