Leetcode - ZigZag Conversion

来源:互联网 发布:android系统优化 编辑:程序博客网 时间:2024/06/05 04:14

问题链接:https://oj.leetcode.com/problems/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".

(这个部分那个例子看的不清楚,要看例子的还是进链接吧)

API:public String convert(String s, int nRows)

分析:这个问题与其说是算法还不如考验你的抽象思维能力和观察能力,事实上用index来代表字符串的具体内容会更加清晰,

如果nRows = 2, index将会如下排列

1   3

2   4

如果nRows = 3, index 将会如下排列

1      5

2  4  6

3      7

如果nRows = 4,   index将会如下排列:

1          7

2      6  8

3  5      9

4          10

事实上到这里应该能看出问题了,假如我们把一个竖行加上中间的内容当做是一个组的话。首先中间的内容的个数是nRows - 2。然后两组之间,第一行和最后一行是没有中间内容的。然后如果有一个变量是表示当前index所在的行数,姑且称之为nColumn, 譬如上面那个例子的2 6 8就是第二行,nColumn = 2。 那么同一组中,同一行的竖行和斜行的index关系应该是:假设斜行index名字叫nX, 竖行index名字叫nL,那么nX = nL + (nRows - nColumn ) * 2, 套入2和6的例子里就是, 6 = 2 + (4 - 2) * 2. 相隔两组同一行元素的关系应该是: 假设第一组的某一行的元素index是 i, 它下一组同一行的元素index是j。 那么j = i + (nRows - 1) * 2。


基于以上的关系,可以知道代码如下:

    public String convert(String s, int nRows) {        if(s == null || s.length() < nRows || nRows == 1)            return s;        StringBuilder res = new StringBuilder();        for(int i = 0; i < nRows; i++){        int distance = 2 * (nRows - 1 - i);        for(int j = i; j < s.length(); j += 2 * (nRows - 1)){        res.append(s.charAt(j));        if(i != 0 && distance != 0 && j + distance < s.length()){        res.append(s.charAt(j + distance));        }                        }        }        return res.toString();    }


0 0