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".
class Solution {
public:
string convert(string s, int nRows) {
int nLength=s.length()-1;
string s1(s.length(),sizeof(char));
int nIndRow,nIndCol;
int nIndS1=0;
if(nRows==1)
return s;
for(nIndRow=0;nIndRow<=nRows-1;nIndRow++)
{
for(nIndCol=0;nIndCol<=nLength/(2*nRows-2);nIndCol++)
{
if(nIndRow==0)
{
s1[nIndS1]=s[nIndCol*(2*nRows-2)];
nIndS1++;
}
if(nIndRow==nRows-1)
{
if(nIndCol!=nLength/(2*nRows-2)||nIndCol*(2*nRows-2)+nRows-1<=nLength)
{
s1[nIndS1]=s[nIndCol*(2*nRows-2)+nRows-1];
nIndS1++;
}
}
if(nIndRow!=0&&nIndRow!=nRows-1)
{
if(nIndCol==nLength/(2*nRows-2))
{
int nLa=nLength%(2*nRows-2);
if(nLa>=nIndRow)
{
s1[nIndS1]=s[nIndCol*(2*nRows-2)+nIndRow];
nIndS1++;
}
if(2*nRows-2-nLa<=nIndRow)
{
s1[nIndS1]=s[nIndCol*(2*nRows-2)+2*(nRows-1)-nIndRow];
nIndS1++;
}
}
else
{
s1[nIndS1]=s[nIndCol*(2*nRows-2)+nIndRow];
nIndS1++;
s1[nIndS1]=s[nIndCol*(2*nRows-2)+2*(nRows-1)-nIndRow];
nIndS1++;
}
}
}
}
return s1;
}
};

本文介绍了一种将字符串以Z字形方式写入指定行数再逐行读取的算法实现。通过C++代码示例展示了如何将输入字符串转换为所需的Z字形布局并返回转换后的结果。
198

被折叠的 条评论
为什么被折叠?



