ZigZag Conversion

来源:互联网 发布:从零开始学日语软件 编辑:程序博客网 时间:2024/06/01 18:27

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   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)nRows=3时候的解析

0        4       8

1   3   5   7

2        6

首先我们计算step为2×nRows-2,nRows为3时候 step为4,

第0行为:第一个数为0,第二个数为第一个数字加上step,第三个数为第二个数加上step。最后一行类似的分析。

其余行:第二个数字3为 step-1,第三个数子5为 (2×step - 第二个数子3),后面是类似的推导。7 = 3×step-5。

最终的代码如下。

(2)当nRows != 3;情况也类似。

 

#include <iostream>#include <string>using namespace std;string convert(string s, int nRows) {int length = s.length();if(nRows <= 1)return s;if(nRows >= 2){string res(length,0);int index = 0;for(int i=0;i<nRows;i++){int step = 2*nRows - 2;if(i==0 || i==(nRows-1)){int num = i;while(num <length){res[index] = s[num];num = num + step;index++;}}if( i>=1&& i<=(nRows-2)){int last = i;int num = i;int sum = 0;while(num <length){res[index] = s[num];sum = sum + step;num = sum - last;last = num;index++;}}}return res;}}int main(void){string s = "PAYPALISHIRING";cout << s << endl;string res = convert(s,2);cout << res << endl;system("pause");return 0;}


0 0
原创粉丝点击