一 题目
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
二 分析
这个题目难度是Medium ,但是相对其他的medium算是简单的了,
题目大意就是给个字符串,求按照行数N按照锯齿格式的字符串转换,给出了例子,看看就容易理解。
2.1 二维数组
就是按照题目要求,花个二维字符组,从竖着列开始对应位置填上字母,第一列为N个字符,然后N-2的长度列是斜线截取赋值,再如一列为N个字符,如此递推。在纸上画画格子很容易看。
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "PAYPALISHIRING";
String res = convert(s,4);
System.out.println(res);
}
public static String convert(String s, int numRows) {
if(s== null || s.length()<= numRows){
return s;
}
char[][] strs = new char[numRows][s.length()];
int len=0;
int j=0;
//填充
while(len<s.length()){
for(int i=0;i<numRows;i++){
if(len<s.length()){
strs[i][j] = s.charAt(len);
len++;
}
}
j++;
for(int l=1;l<=numRows-2;l++ ){
if(len<s.length()){
strs[numRows-1-l][j] = s.charAt(len);
len++;
j++;
}
}
}
String res ="";
for(int r=0;r<numRows;r++){
for(int l=0;l<s.length();l++){
if(strs[r][l]!='\0'){
res =res+ strs[r][l];
}
}
}
return res;
}
这样二维数组遍历就很慢了。O(N^2)
Runtime: 27 ms, faster than 11.40% of Java online submissions for ZigZag Conversion.
Memory Usage: 39.9 MB, less than 52.13% of Java online submissions forZigZag Conversion.
2.2 字符串租
如何降维提高速度呢?
不是二维数组,只看行的情况下,以例二的数据,在观察这个字符串的分布规律:
PAYPALISHIRING
01232101232101
有没有发现新规律呢?
就是以N-1的行号为边界,先增加再减少的。这有点想之前看的数学的求余的那种思路,先根据规律对原字符进行分组,再根据分组的结果从小到大输出。
public static String convert(String s, int numRows) {
if(s== null || s.length()<= numRows|| numRows==1){
return s;
}
String[] strs = new String[numRows];
for(int r=0;r<numRows;r++){
strs[r] ="";
}
int row =0;
int sign =1;
for( int i= 0; i<s.length() ;i++){
strs[row] = strs[row] +s.charAt(i);
if(row ==0){
sign =1;
}else if(row == numRows-1){
sign =-1;
}
row = row+sign;
}
String res ="";
for(int r=0;r<numRows;r++){
res = res+strs[r];
}
return res;
}
Runtime: 14 ms, faster than 31.28% of Java online submissions for ZigZag Conversion.
Memory Usage: 38.3 MB, less than 86.17% of Java online submissions forZigZag Conversion.
官网的solution,还没看。todo..