leetCode #6 ZigZag Conversion

来源:互联网 发布:java实验指导书答案 编辑:程序博客网 时间:2024/04/19 13:26

题目:将一个字符串z字形排列,再按阅读顺序输出新的字符串

分析:其实新字符串中每个字符的位置都可以算出来。就是将斜对角线的字符拍扁到一条线上,就可以看出是2行的关系。

答案:

class Solution {public:string convert(string s, int nRows) {string result = "";int ind = 0;bool isOdd = true;int j = 0;if (nRows <= 1)return s;while (j < nRows && result.length() < s.length()){result = result + s[ind];int step = 0;// set stepif (j == 0 || j == nRows - 1){ step = 2 * (nRows - j - 1) + 2 * j ;}else{if (isOdd){step = 2 * (nRows - j - 1);isOdd = !isOdd;}else{step = 2 * j;isOdd = !isOdd;}}// if over boundaryif ((ind + step) >= s.length()){j++;ind = j;isOdd = true;}else{ind += step;}}return result;}};

0 0
原创粉丝点击