题目:
将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 “PAYPALISHIRING” 行数为 3 时,排列如下:
P A H N
A P L S I I G
Y I R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“PAHNAPLSIIGYIR”。
请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
示例 1:
输入:s = “PAYPALISHIRING”, numRows = 3
输出:“PAHNAPLSIIGYIR”
示例 2:
输入:s = “PAYPALISHIRING”, numRows = 4
输出:“PINALSIGYAHRPI”
解释:
P I N
A L S I G
Y A H R
P I
示例 3:
输入:s = “A”, numRows = 1
输出:“A”
提示:
1 <= s.length <= 1000
s 由英文字母(小写和大写)、’,’ 和 ‘.’ 组成
1 <= numRows <= 1000
初步思路:
经过观察,在对应位置的元素(即在第几行的位置)的下标有一定的规律,比如在下实例中第一行P在原字符串中下标为0,第一行A为4,H为8,N为12,%4都得0,ALIG得1,YIR得2,PSI得3,所以我们用他们的下标%4就可以知道他们所在的行号了。
P A H N
A P L S I I G
Y I R
对于这个例子就是%6,同时1,5在一行 2,4的在一行,拥有一定的规律
P I N
A L S I G
Y A H R
P I
代码:哈哈也可以通过
class Solution {
public String convert(String s, int numRows) {
if(numRows == 1)
return s;
int len = Math.min(s.length(),numRows);
String[] rows = new String[len];
int temps = numRows*2-2;
for(int i = 0; i< len;i++)
rows[i]="";
for(int i = 0;i < s.length();i++)
{
for(int j = 0;j < numRows;j++)
{
if(i % temps == j || i % temps + j == temps)
rows[j] += s.substring(i,i+1);
}
}
String ans = "";
for(String row : rows)
{
ans += row;
}
return ans;
}
}
看了题解之后
我们逐字符读入这个字符串读,然后按照一定的规律去放置这个Z字型的每个字符,从行号为0开始放置一个字符,此时向行号增大的方向继续放置字符,直到行号达到numRows-1为最大值,此后行号逐字符减小直至为0,然后继续转向增加。
class Solution {
public String convert(String s, int numRows) {
if(numRows == 1)
return s;
int len = Math.min(s.length(),numRows);
String[] rows = new String[len];
for(int i = 0; i< len;i++)
rows[i]="";
int loc = 0;
boolean down = false;
for(int i = 0; i < s.length();i++)
{
//遍历s,如果此时字符的行号为0或者在末行,说明方向要变化
rows[loc] += s.substring(i,i+1);
if(loc == 0 || loc == numRows - 1)
{
down = !down;
}
loc += down ? 1 : -1;//如果方向为正即true则行号加1,为负则-1
}
String ans = "";
for(String row : rows)
{
ans += row;
}
return ans;
}
}