[leetcode#6]ZigZag Conversion

[leetcode#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”.
題目意思如圖字符串用8行進行列排列,題目要求轉化成行排列時的字符串輸出

這裏寫圖片描述
思路:
找出規律,在輸出第0行時,第一個字符串爲s[0],接着循環加上(numRows-1)*2,輸出第0行第2個字符,第3個字符類推到s[j]>n
換成第1行輸出,第1行第1個字符串爲 s[1],
接着循環加上(numRows-1)*2-1*2, 1*2, (numRows-1)*2-1*2, 1*2兩個數字交換相加類推到s[j]>n
第p行第一個字符爲s[p],接着循環加上(numRows-1)*2-p*2, p*2, (numRows-1)*2-p*2, p*2兩個數字交換相加類推到s[j]>n
最後一行跟第一行一樣,一直循環加(numRows-1)*2
在numrows等於1, 需注意一直加1.

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