
将字符串 "PAYPALISHIRING" 以Z字形排列成给定的行数:
1 2 3
|
P A H N A P L S I I G Y I R
|
之后从左往右,逐行读取字符:"PAHNAPLSIIGYIR"
实现一个将字符串进行指定行数变换的函数:
1
|
string convert(string s, int numRows);
|
1 2 3 4 5 6 7 8 9 10 11
|
输入: s = "PAYPALISHIRING", numRows = 3 输出: "PAHNAPLSIIGYIR"
输入: s = "PAYPALISHIRING", numRows = 4 输出: "PINALSIGYAHRPI" 解释:
P I N A L S I G Y A H R P I
|
参考代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
#include<string> using namespace std; string (string s, int numRows) { string result="";; string *p=new string[numRows]; string tmp="a"; int num=0; int step=numRows+(numRows-2); int i=0; while(i<s.size()) { for(int j=0;j<numRows&&i<s.size();j++) { tmp[0]=s[i++]; p[j]=p[j]+tmp; } for(int j=numRows-2;j>0&&i<s.size();j--) { tmp[0]=s[i++]; p[j]=p[j]+tmp; } } for(i=0;i<numRows;i++) { result+=p[i]; } return result; } int main() { string test="PAYPALISHIRING"; cout<<convert(test,4)<<endl; return 0; }
|
小结
近期评论