.题目描述:将一个给定字符串 s
根据给定的行数 numRows
,以从上往下、从左到右进行 Z 字形排列。比如输入字符串为 "PAYPALISHIRING"
行数为 3
时,排列如下:
P A H N A P L S I I G Y I R
学习:
N字形变换后每一行可以看作是一个字符串,最后将字符串加起来输出就行。定义一个有numRows个字符串的数组,那问题就在对于字符串s的每一个字符加到数组的哪一个后面,由于N字形,如果4行,那加的顺序就是1234 32 1234 ....在过程中如果超出s的长度就退出就行了
class Solution {
public:
string convert(string s, int numRows)
{
vector<string> temp(numRows);
for(int i=0;i<numRows;i++)
{
temp[i]="";
}
string result="";
int times=0;
while(1)
{
for(int i=0;i<numRows;i++)
{
temp[i]=temp[i]+s[times];
times++;
if(times>=s.length())
break;
}
if(times>=s.length()) break;
for(int i=numRows-2;i>0;i--)
{
temp[i]=temp[i]+s[times];
times++;
if(times>=s.length()) break;
}
if(times>=s.length()) break;
}
for(int i=0;i<numRows;i++)
{
result=result+temp[i];
}
return result;
}
};
官方题解:
1.矩阵存储(计算需要几列)
2.压缩矩阵(其实和用字符串是一样的,用可变数组向后添加)
3.直接构造