关于LeetCode中ZigZag Conversion一题的理解

来源:互联网 发布:成塔软件 编辑:程序博客网 时间:2024/06/05 04:19

题目如下:

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   NA P L S I I GY   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".

    题目关键信息:

    (1)给定了行数;

    (2)Z形的这种字符串应该分两种情况处理;第一种是“垂直”部分,即题目例子中第一列“PAY”,第三列“ALT”这种;第二种就是”斜线“的,如”YPA“和”ISH“这种类型的。

    我这里直接搬运评论区代码了,已Accepted的,如下所示:

    public String convert(String s, int numRows) {            char[] c = s.toCharArray();            int len = c.length;            StringBuffer[] sb = new StringBuffer[numRows];            for (int i = 0; i < sb.length; i++) sb[i] = new StringBuffer();            int i = 0;            while (i < len) {                for (int idx = 0; idx < numRows && i < len; idx++) // vertically down                    sb[idx].append(c[i++]);                for (int idx = numRows-2; idx >= 1 && i < len; idx--) // obliquely up                    sb[idx].append(c[i++]);            }            for (int idx = 1; idx < sb.length; idx++)                sb[0].append(sb[idx]);            return sb[0].toString();    }
    主要看一下while循环中的for循环,第一个for循环处理的是”垂直“部分,非常容易理解;第二个就稍微难一点,”斜线“部分的第一个和最后一个元素我们都是不需要在这里处理的,应该直接用”垂直“部分处理第一个元素和最后一个元素。那剩下的部分就是第二个元素和倒数第二个元素以及他们之中的部分,这个范围是什么?这个范围就是大于等于1小于等于行数减2(因为行数减1是最后一个元素)。

    while循环结束,将分散的stringbuffer类型的数组整合成一个stringbuffer对象,然后直接使用toString转化成String类型返回即可。

    最近比较忙,还是强行在LeetCode找题做,毕竟如果不会还有评论区大神,不过感觉十一之后就能正常愉快地好好玩耍了。

1 0