转载:https://www.nowcoder.com/questionTerminal/d3583975276743d3befe2ddd43156d14
问题描述:字符串PAYPALISHIRING转换为:
P A H N A P L S I I G Y I R
输出为PAHNAPLSIIGYIR
解析:字符串循环周期为2*row-2(两列减去头尾的两个)
string convert(string s, int nRows) {
if (nRows <= 1) return s;
int t = nRows + nRows - 2; //求出循环周期
string res = "";
vector<string> m(nRows, res);
for (int i = 0; i < s.length(); i++)
{
int a = i%t;
if (a < nRows) //往下走
m[a] += s[i];
else //往上走
m[t - a] += s[i];
}
for (int i = 0; i < nRows; i++)
res += m[i]; //合并
//res+=m[i]+" ";
return res;
}
int main()
{
string s = "PAYPALISHIRING";
string res = convert(s, 4);
cout << res << endl;
system("pause");
}
本文介绍了一种将字符串按Z形排列进行转换的算法实现。通过定义字符串的循环周期为2*行数-2,并利用此周期进行字符的重新排列,最终合并成新的字符串。该算法适用于如PAYPALISHIRING这样的字符串转换为PAHNAPLSIIGYIR的场景。
514

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



