题目描述:
将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 “PAYPALISHIRING” 行数为 3 时,排列如下:
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“PAHNAPLSIIGYIR”。
思路:只要获得每个字符的行数即可,行数规律(1…numRows…1…),再利用桶排序的思想就可以一次遍历。
代码:
class Solution {
public String convert(String s, int numRows) {
int[] row = new int[s.length()];
int j = 1; //当前行数
int k = 1; //1 up; 0 down;
int[] rowNum = new int[numRows+1]; //每行起始位置
int[] rowNumSort = new int[numRows+1]; //每行已排个数
if(numRows==1) return s;
for(int i=0;i<s.length();i++){
row[i] = j;
rowNum[j]+=1;
if(k==1){
j+=1;
}else{
j-=1;
}
if(j == numRows){
k = 0;
}else if(j==1){
k = 1;
}
}
for(int i =1 ;i<=numRows;i++){ //桶排序基础操作
rowNum[i]+=rowNum[i-1];
}
StringBuilder str = new StringBuilder(s);
for(int i =0;i<s.length();i++){
int z = row[i];
str.setCharAt(rowNum[z-1]+rowNumSort[z],s.charAt(i));
rowNumSort[z]+=1;
}
return str.toString();
}
}