LeetCode(6)--ZigZag Conversion

来源:互联网 发布:mac怎么远程桌面连接 编辑:程序博客网 时间:2024/06/05 02:07

题目如下:
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”.

解题思路:
思路1:第一次使用了一个临时的char二维数组,具体的方法是遍历整个字符串,先将整行都有字符的填满,然后再对有空格的填满,对数据一列一列的操作。

char[][] zig = new char[numRows][s.length()];       String str = "";       int i = 0;       int k = 0;       while(i < s.length()){            for (int j = 0; j < numRows && k < s.length(); j++)                 zig[j][i] = s.charAt(k++);            for (int j = numRows - 2; j > 0  && k < s.length(); j--)                 zig[j][++i] = s.charAt(k++);            i++;       }       for (int j = 0; j < zig.length; j++) {             for (int j2 = 0; j2 < zig[j].length; j2++) {                if(Character.isLetterOrDigit(zig[j][j2])){                    str += zig[j][j2];                }            }       }       return str;

但是,问题来了对于有其他字符的字符串处理起来就明显吃力,比如“,。”等Character.isLetterOrDigit()会将非字母和数字类型的其他字符过滤掉,因此,该方法提交之后Error。
思路2:沿着思路1的方法走,使用一个字符串数组,再赋值的时候就将空格等其他字符去除掉。
提交的代码:

if(numRows == 1) return s;        String[] zig = new String[numRows];        String str = "";        for (int i = 0; i < zig.length; i++) zig[i] = "";        for( int k = 0; k < s.length();){            for (int j = 0; j < numRows && k < s.length(); j++)                 zig[j] += s.charAt(k++);            for (int j = numRows - 2; j > 0  && k < s.length(); j--)                 zig[j] += s.charAt(k++);        }        for (int i = 0; i < zig.length; i++) str += zig[i];        return str;

参考:
http://www.cnblogs.com/sanghai/p/3632528.html

0 0
原创粉丝点击