6. ZigZag Conversion

来源:互联网 发布:自学编程先看什么书 编辑:程序博客网 时间:2024/06/10 12:55

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”.

这题很简单,主要就是找到位置变化的规律,不涉及什么典型算法或者数据结构。

方法一:时间O(n), 空间O(n)
建立一个vector< string>, 将输入string里每一个char依次放入对应的行中。基本规律就是,插入具有重复性,每隔2*numRows - 2 重复一遍。
代码:

string convert(string s, int numRows) {    vector<string> ans(numRows);    if (s.size() == 0 || numRows <= 1) return s;    int i = 0, j = 0;    while (i < s.size()) {        if (j < numRows) {            ans[j++].push_back(s[i++]);        }        else if (j < 2 * numRows - 2){            ans[2 * numRows - 2 - j].push_back(s[i++]);            j++;        } else {            j = 0;        }    }    string res;    for (i = 0; i < numRows; i++) {        res += ans[i];    }    return res;}

方法二:时间O(n), 空间O(1)
不用将每行保存,直接在原string上按顺序找到对应元素。
代码:

string convert(string s, int numRows) {    if (s.size() == 0 || numRows == 1) return s;    string ans = "";    int i = 0, j = 0;    int jump = 2 * numRows - 2;    while (j < numRows) {        i = j;        while (i < s.size()) {            ans += s[i];            i += jump;            if (j != 0 && j != numRows - 1 && i - 2 * j < s.size()) {                ans += s[i - 2 * j];            }        }        j++;    }    return ans;}