6. ZigZag Conversion

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

所謂的zigzag pattern型就是指,我們以倒N型的順序來讀數。
三行的情況:
三行的情況
四行的情況:
四行的情況
我們輸入的text是以這種模式來排布的,之後我們需要將其以橫向的、從左到右的、我們習慣的閱讀方式來從新排布,將其輸出。

一種解題思路就是,我們使用數個字符串(設爲row[n]),存下每一行的字符,最後將每行的字符串疊連起來,就是我們想要的結果。以一次下、一次上爲一個單元(一共2*nRows-2個字符),這樣我們就能算出每個輸入的text中的每個字符分別對應某個單元的第幾個字符,也就可以計算得到改字符的行數。也就是說,我們能夠計算出text[i],text的第i個字符是屬於第幾行的,之後將其添加到row中。這樣,我們只需要走一次text,就能夠得到每行依此有哪些字符,之後將其首尾相連,得到的就是輸出了。

參考代碼如下:

class Solution {
public:
    string convert(string s, int numRows) {
        int len = s.length();
        if(len <= 1 || numRows == 1)
            return s;
        string temp[numRows];
        for(int i = 0; i < numRows; i++)
            temp[i] = "";
        for(int i = 0; i < len; i++) {
            int index = i % (2*numRows-2);
            if(index >= numRows)
                index = 2 * numRows - 2 - index;
            temp[index] += s[i];
        }
        string result = "";
        for(int i = 0; i < numRows; i++)
            result += temp[i];
        return result;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章