首页 > 学院 > 开发设计 > 正文

6. ZigZag Conversion

2019-11-06 08:17:47
字体:
来源:转载
供稿:网友
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 NA P L S I I GY 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 n) { string re; if(n==1) return s; for(int t=0;t<n;t++) if(t==0||t==n-1)//开头和结尾行 { int cnt=0; while(t+cnt*(2*n-2)<s.size()) re.push_back(s[t+(2*n-2)*(cnt++)]); } else { int cnt=2; re.push_back(s[t]); while(1) { if(cnt*(n-1)-t<s.size()) re.push_back(s[cnt*(n-1)-t]); else break; if(cnt*(n-1)+t<s.size()) re.push_back(s[cnt*(n-1)+t]); else break; cnt+=2; } } return re; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表