问题描述:
The string
"PAYPALISHIRING"
is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N A P L S I I G Y I RAnd then read line by line:
"PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3)
should return
"PAHNAPLSIIGYIR"
.
解题思路:
该题是让找出“之”字型后的字符串输出,那么直接用numRows个结果集存储结果,输出即可。向下为numRows循环,斜角线循环为numRows-2:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
string convert(string s, int numRows) {
if(s.empty()||numRows==1) return s;
string *res=new string[numRows];
int i=0,j,gap=numRows-2;
while(i<s.size()){
for(j=0;i<s.size()&&j<numRows;++j)
{
res[j]+=s[i++];
cout<<res[j]<<endl;
cout<<s[i]<<endl;
}
for(j=gap;i<s.size()&&j>0;--j)
{
res[j]+=s[i++];
}
}
string str="";
for(i=0;i<numRows;++i)
str+=res[i];
return str;
}
#include <string>
#include <cstring>
using namespace std;
string convert(string s, int numRows) {
if(s.empty()||numRows==1) return s;
string *res=new string[numRows];
int i=0,j,gap=numRows-2;
while(i<s.size()){
for(j=0;i<s.size()&&j<numRows;++j)
{
res[j]+=s[i++];
cout<<res[j]<<endl;
cout<<s[i]<<endl;
}
for(j=gap;i<s.size()&&j>0;--j)
{
res[j]+=s[i++];
}
}
string str="";
for(i=0;i<numRows;++i)
str+=res[i];
return str;
}
int main()
{
string a="PAYPALISHIRING";
string s;
s=convert(a,3);
cout << s << endl;
return 0;
}