1. 程式人生 > >第十九周LeetCode演算法題

第十九周LeetCode演算法題

題目名稱:6. ZigZag Conversion

題目難度:Medium

題目描述:

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樣式到底是一個什麼樣的樣式,查了一下才知道是這樣子的:

Δ=2n-2    1                           2n-1                         4n-3
Δ=        2                     2n-2  2n                    4n-4   4n-2
Δ=        3               2n-3        2n+1              4n-5       .
Δ=        .           .               .               .            .
Δ=        .       n+2                 .           3n               .
Δ=        n-1 n+1                     3n-3    3n-1                 5n-5
Δ=2n-2    n                           3n-2                         5n-4

於是就有了思路,很直接地用一個二維矩陣儲存起來,然後再按要求輸出就行,比較需要注意的是矩陣的大小,可以使用壓縮處理將中間一些比較稀疏的列合在一起。
最後AC的程式碼是:

class Solution {
public:
    string convert(string s, int numRows) {
        if (s.size() <= 1 || numRows == 1) return s;
        int numCols;
        if (s.size() <= numRows) {
            numCols = 1;
        } else
{ int t = numRows * 2 - 2; int temp = s.size() / t * 2; int toIf = s.size() % t; if (toIf < numRows) numCols = temp + 1; else numCols = temp + 2; } vector<char> temp(numCols, '-'); vector<vector<char>> v; v.assign(numRows, temp); int index = 0; bool flag = 0; for (int j = 0; j < numCols; ++j) { if (j % 2 == 0) { for (int i = 0; i < numRows; ++i) { v[i][j] = s[index++]; if (index >= s.size()) { flag = 1; break; } } } else { for (int i = numRows - 2; i > 0; --i) { v[i][j] = s[index++]; if (index >= s.size()) { flag = 1; break; } } } if (flag) break; } string result; for (int i = 0; i < numRows; ++i) { for (int j = 0; j < numCols; ++j) { if (v[i][j] != '-') { result += v[i][j]; } } } for (int i = 0; i < numRows; ++i) { for (int j = 0; j < numCols; ++j) { cout << v[i][j] << ' '; } cout << endl; } cout << endl; return result; } };