將字符串 "PAYPALISHIRING" 以Z字形排列成給定的行數(shù):
P A H N
A P L S I I G
Y I R
之后從左往右,逐行讀取字符:"PAHNAPLSIIGYIR"
實(shí)現(xiàn)一個(gè)將字符串進(jìn)行指定行數(shù)變換的函數(shù):
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
代碼
public:
string convert(string s, int numRows)
{
if(numRows==1)//邊界情況,如果只有1行,那么直接返回原本的字符串
return s;
int s1=s.size(),s2=2*numRows-2,s3=s2,index=0,index1,count=0;//s2表示山峰的元素個(gè)數(shù)
string res=s;
for(int i=0;i<numRows;i++)//逐行處理
{
index1=index;//記錄一下index的值,最開始為0,接著是1,再接著是2……
while(index<s1)//每一行中只要坐標(biāo)index不超過字符串的長度,那么不斷處理
{
if(s3==s2)//如果是第一行
{
res[count]=s[index];
index+=s3;
count++;
}
else if(s3==0)//如果是最后一行
{
res[count]=s[index];
index+=(s2-s3);
count++;
}
else//如果是中間行
{
res[count]=s[index];
index+=s3;
count++;
if(index<s1)//不能超過字符串的長度
{
res[count]=s[index];
index+=(s2-s3);
count++;
}
}
}
s3-=2;//處理完一行之后,s3減去2
index=index1+1;//更新index的值
}
return res;//最后返回新的字符串
}