leetcode题目-第六题 Z字形变换
leetcode-cn.com(领扣),一个不错的代码练习网站
第六题 https://leetcode-cn.com/problems/zigzag-conversion/description/
打败 88.15 %选手
题目:
将字符串 "PAYPALISHIRING" 以Z字形排列成给定的行数:
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
我的答案:
class Solution {
public:
string convert(string s, int numRows)
{
if(s.length()==1||s.length()==2||numRows==1){return s;}
string finals="";
string out[numRows+1];
int j=0;
int i=0;
int a,b;
int h=1;
int l = s.length();
while(h<=numRows)
{
if(h==1)
{
for(j=0;(2*numRows-2)*j<=l-1;j++)
{
out[1].append(1,s[(2*numRows-2)*j]);
}
}
else if(h==numRows)
{
for(j=0;(2*numRows-2)*j+numRows-1<=l-1;j++)
{
out[numRows].append(1,s[(2*numRows-2)*j+numRows-1]);
}
}
else
{
for(j=0;(2*numRows-2)*j<=l-1;j++)
{
a = (2*numRows-2)*j+h-1;
b = (2*numRows-2)*(j+1)-h+1;
if(a!=b&&a<=l-1&&b<=l-1&&s[a]!='\0'&&s[b]!='\0'){out[h].append(1,s[a]);out[h].append(1,s[b]);}
if(a!=b&&a<=l-1&&b>l-1&&s[a]!='\0'){out[h].append(1,s[a]);}
if(a!=b&&a>l-1){;}
if(a==b&&a<=l-1&&b<=l-1&&s[a]!='\0'&&s[b]!='\0'){out[h].append(1,s[a]);}
}
}
h++;
}
for(i=2;i<=numRows;i++)
{out[1]+=out[i];}
return out[1];
}
};

微信扫一扫,打赏作者吧~