题目描述
题解
像这种字符串打印出某种特定顺序的题目还是不要使用蛮力,最好找出其中的规律再写代码也不迟
从字符串的结果可以看出如下结果
0 P A H N
1 A P L S I I G
2 Y I R
PAYPALISHIRING
0121/0121/0121/01
周期的长度为3*2 - 2 = 4
代码
class Solution {
public String convert(String s, int numRows) {
int circle = numRows * 2 - 2;
String[] res = new String[numRows];
// 记录当前的坐标位置
int count = 0;
// 记录当前的周期的长度
int len = 0;
//遍历整个字符串,在一个周期内将坐标的位置根据已有规律使用,将对应的字符放到对应的数组的某一行中。
for(char c : s.toCharArray()){
if(res[count] == null){
res[count] = c + "";
}else{
res[count] = res[count] + c;
}
len++;
if(count < numRows && len < circle && len < numRows){
count++;
}else if(len < circle && len >= numRows){
count--;
}
if(len == circle){
len = 0;
count = 0;
}
}
String result = "";
for(String str:res){
if(str != null){
result = result + str;
}
}
return result;
}
}