6. ZigZag Conversion

来源:互联网 发布:linux 混合硬盘 编辑:程序博客网 时间:2024/06/13 23:47

题目:ZigZag Conversion

原题链接:https://leetcode.com/problems/zigzag-conversion/
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………N
…A…P…L…S…..I…..I…..G
……Y………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”.

给出一个字符串,然后按照一定的列数来锯齿状重新排列,再按照每一行重新组合起来,求组成的新的字符串。
例:
给出字符串”PAHNAPLSIIGYIR”,列数为3,按照锯齿状排列如上图,那么重新组合成字符串为”PAHNAPLSIIGYIR”。

第一种方法可以模拟它的过程,假设有 n 行,那么就设 n 个字符串,然后把初始的字符串里面的字符一个一个的赋值给这 n 个字符串,最后把这 n 个字符串相加。不过这种方法比较耗时。

第二种方法是直接计算每一行的下标,然后相加。对于给定的行数 n ,那么每一行的相邻两个元素在原字符串中的间隔是有迹可循的。以之前的例子中第二行的第一个字符 ‘A’ 来说,这一行的下一个字符和它的下标间隔(可以看成是从下往上的间隔)是(假设总行数为numRows,当前为第 i 行)2 * (numRows - 1 - i) ,再下一个’ L ‘和 ’ P ‘的间隔(可以看成是从上往下的间隔)是2 * i,然后依次这样相加,就是这一行所有元素的下标。当然别忘了注意第一行和最后一行的特殊情况,这两行的两种间隔都有一种是0,注意不要重复相加元素就行。

代码如下:

class Solution {public:    string convert(string s, int numRows) {        int len = s.length();        if(len < numRows || numRows == 1) return s;        string ans = "";        for(int i = 0; i < numRows; ++i) {            ans += s[i];            int d1 = 2 * (numRows - 1 - i), d2 = 2 * i;            int ci = i + d1;            if(d1 && d2) {                while(ci < len) {                    ans += s[ci];                    ci += d2;                    if(ci < len) ans += s[ci];                    ci += d1;                }            }else if(d1) {                while(ci < len) {                    ans += s[ci];                    ci += d1;                }            }else{                ci += d2;                while(ci < len) {                    ans += s[ci];                    ci += d2;                }            }        }        return ans;    }};
0 0
原创粉丝点击