美文网首页
6. ZigZag Conversion(Z字形字符串转换)

6. ZigZag Conversion(Z字形字符串转换)

作者: 斌小斌 | 来源:发表于2019-10-06 19:21 被阅读0次

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 s, int numRows);
Example 1:

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

P I N
A L S I G
Y A H R
P I
一:矩阵处理法(模拟人的算法思想)

class Solution {
    public String convert(String s, int numRows) {
        if(s.length()==0||s.length()==1||numRows==1)
            return s;
        String res="";
        int hang=s.length()/(numRows-1)+1;
        char[][] str=new char[hang][];
        int l=0;
        int lie=0;
        for(int i=0;i<str.length;i++) {
            str[i]=new char[numRows];
            for(int j=0;j<str[i].length;j++) {
                str[i][j]='0';
            }
        }
        for(int i=0,h=0;l<s.length();i++,h++){
            if(h%2==0){ 
                for(int j=0;j<numRows-1&&l<s.length();j++,l++){
                    str[i][j]=s.charAt(l);
                }
            }
            if(h%2==1){
                for(int j=numRows-1;j>0&&l<s.length();j--,l++){
                    str[i][j]=s.charAt(l);
                }
            }
            lie=i+1;
        }
        for(int j=0;j<numRows;j++){
            for(int i=0;i<lie;i++){
                if(str[i][j]!='0') {
                    res+=str[i][j];
                }
            }
        }
        return res;
    }
}

思想:该算法主要是通过模拟人类的思想,将转换的Z字形字符串转换为矩阵储存。再将矩阵从左到右转换为结果即可。优点是算法思想贴近人类思维,易于实现。
知识点:当在方法中定义变量时,需要进行初始化,否则是不能使用该变量的。

           char[][] str=new char[hang][];

JAVA中二维数组的定义时与C语言不同,C语言可以省略第一维的行数,但是不能省略第二维;而JAVA可以省略第二维的列数,不能省略第一维的行数。

相关文章

网友评论

      本文标题:6. ZigZag Conversion(Z字形字符串转换)

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