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”.
思路:
找規律:這是一個解決問題問題的方法。當我們遇到難纏的問題的時候,我們先考慮簡單的情形,看看能不能找到規律。這個題目,我們通過寫出來這些特殊情況,我們發現如下規律,這裏我們假設我們分成m排:
1 第i排從i開始
2 第i排兩個數的間隔是2(i-1),2(m-i)交替
代碼:

class Solution {
public:
    string convert(string s, int nRows) {
        string result;
        if(nRows==1) return s;
        for(int i=0;i<nRows;i++)
        {
            int j=i;
            bool flag=true;
            while(j<s.size())
            {
                result.push_back(s[j]);
                if(i==0 || i==nRows-1) j+=2*(nRows-1);
                else{
                    if(flag) 
                    {
                        j+=2*(nRows-i-1);
                        flag=false;
                    }
                    else{
                        j+=2*i;
                        flag=true;
                    }
                }
            }

        }
        return result;
    }
};
發佈了19 篇原創文章 · 獲贊 7 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章