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 RAnd 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"
.
基本的实现题。不过需要仔仔细细的想想画画分析。设字符串长度为n。比较简单的做法是产生一个(numRows-1)*numRows矩阵把输入字符串按要求扔进去,再逐行遍历。但这么做浪费不少空间,抠门一点换个思路。
以题目中的PAYPALISHIRING为例。我们在纸上构建如下矩阵
不同的颜色的字符串代表一组,其个数为k=2*numRows-2。我以i,j为坐标定位矩阵。0<= i < numRows, 0<=j<=n/k。我们逐行逐列遍历矩阵,在每一个i,j处都可以定位到原矩阵相应字符的位置,依次把该字符加入结果尾部即可。定位公式如下:(1)if i==0 or i==numRows-1, index = i+k*j. 此时每个i,j处只要加入一个字符(2) otherwise,此时每个i,j处要加入两个字符,index1 = i+k*j, index2 = (j+1)*k-(i-1)-1 = (j+1)*k-i。注意对index要判断是否小于n,大于n的舍弃。代码如下
public class Solution {
public String convert(String s, int numRows) {
if(s==null) return null;
int n = s.length();
if(n==0) return "";
if(numRows==1 || numRows>=s.length()) return s;
int k = 2*numRows-2;
StringBuffer buffer = new StringBuffer();
//ArrayList<StringBuffer> list = new ArrayList<StringBuffer>();
for(int i = 0; i<numRows; i++){
for(int j=0;j<=n/k;j++){
if(i==0 || i==numRows-1){
int index = i + j*k;
if(index<n){
buffer.append(s.charAt(index));
}
}else{
int index1 = i+j*k;
int index2 = (j+1)*k-i;
if(index1<n){
buffer.append(s.charAt(index1));
}
if(index2<n){
buffer.append(s.charAt(index2));
}
}
}
}
return buffer.toString();
}
}
时间复杂度为O(N),空间复杂度如果不算结果为1.