您的位置:首页 > 编程语言 > C语言/C++

ZigZag Conversion

2015-07-19 15:51 316 查看
一、题目内容: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   R

And 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"
.
二、代码参考:

解法1:

<pre name="code" class="cpp"> string convert(string s, int numRows) {
if(s.empty()||s.size()<=numRows || numRows<=1)
return s;
//
vector<string> vec;
while(s.size()>2*numRows-2)
{
vec.push_back(s.substr(0,2*numRows-2));
s.erase(0,2*numRows-2);
}
if(!s.empty())
vec.push_back(s);
//
int i,j;
string str;
for(i=0;i<numRows;i++)
{
for(j=0;j<vec.size();j++)
{
if(i==0)
{
str.push_back(vec[j][i]);
}
else
{
if(vec[j].size()>i)
str.push_back(vec[j][i]);
if(i<numRows-1 &&vec[j].size()>2*numRows-i-2)
str.push_back(vec[j][2*numRows-i-2]);
}
}

}
return str;
}



解法2:

string convert(string s, int numRows) {
if(s.empty()||s.size()<=numRows ||numRows<=1)
return s;
//
string str;
int i,j;
for(i=0;i<numRows;i++)
{
for(j=0;j<s.size();j+=2*numRows-2)
{
if(i==0)
{
str.push_back(s[j+i]);
}
else if(i==numRows-1)
{
if(j+i<s.size())
str.push_back(s[j+i]);
}
else
{
if(j+i<s.size())
str.push_back(s[j+i]);
if(j+2*numRows-2-i<s.size())
str.push_back(s[j+2*numRows-2-i]);

}
}
}

return str;
}

三、执行结果
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息