1. 程式人生 > >一道小學數學題:ZigZag Conversion

一道小學數學題: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 s, int numRows);

通俗一點來說,就是將給定字串以N字形輸出之後再去掉空格回車按行順序得到一個全新的字串。
來看幾個例子:

Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
---

Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P     I    N
A   L S  I G
Y A   H R
P     I

求解演算法

一開始沒有注意到要去掉空格,發現之後全都註釋掉對應部分就過了。思路很簡單,就是發現規律而已。

class Solution {
public:
    string convert(string s, int numRows) {
    	if (numRows == 1) {
    		return s;
		}
        int L = s.length();
        int a = L/(2*numRows-2), b = L%(2*numRows-2);
        int numCols = a*(numRows-1)+1+b/numRows*(b%numRows);
        string ss = "";
        int index =
0; for (int i = 0; i < numRows; i++) { for (int j = 0; j < numCols; j++) { a = j%(numRows-1); if (a > 0 && a+i != numRows-1) { //ss += " "; } else { b = j/(numRows-1); index = b*(2*numRows-2)+(a==0?i:numRows+a-1); if (index < s.length()) { ss += s[index] ; } /*else { ss += ' '; }*/ } } //ss += '\n'; } return ss; } };

其實還有一種思路就是,先獲得每一列對應的字串,然後按行拼接起來,這樣很容易實現,但是複雜度就上去了。