LeetCode 6. ZigZag Conversion ( C )-Medium

題目為給定一個字串,把該字串照 zigzag pattern (鋸齒型) 排列,

如下圖所示依照紅色箭頭依序排列,此圖假設 Row 為 4,並依照排序後的每一列 ( Row ) 字元輸出,可以參考下方題目原文的範例。

題目與範例如下

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);
 

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
Example 3:

Input: s = "A", numRows = 1
Output: "A"
 

Constraints:

1 <= s.length <= 1000
s consists of English letters (lower-case and upper-case), ',' and '.'.
1 <= numRows <= 1000

我的解題策略為,依照列 ( Row ) 一列一列輸出,透過 Step 做跳躍, Step 的大小為 ( numRows – 1 ) x 2 ,並於第二列之後採用先輸出減 row 的值,在輸出加 row 的值,並於最後一列 ( Row ) 時,保護不重複輸出。

下面是我的程式碼

char * convert(char * s, int numRows){
    if(strlen(s) == 1 || numRows == 1)
        return s;
    int step = (numRows-1)*2, rIndex = 0,strl = strlen(s);
    char *r = (char *)malloc((strl+1)*sizeof(char));
    r[strl] = '\0';
    for(int i = 0;i<numRows;i++){
        int jump = 0;
        while(jump<strl){
            if(jump+i<strl && i!=(numRows-1)){
                r[rIndex] = s[jump+i];
                rIndex++;
            }
            jump+=step;
            if(jump-i<strl && i!=0){
                r[rIndex] = s[jump-i];
                rIndex++;
            }
        }
    }
    
    return r;
}

下面是時間與空間之消耗

Runtime: 0 ms, faster than 100.00 % of C online submissions for ZigZag Conversion.

Memory Usage: 6.5 MB, less than 86.07 % of C online submissions for ZigZag Conversion.

下一題連結 : LeetCode 7. Reverse Integer ( C )-Easy

Add a Comment

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *