1. 程式人生 > >LeetCode-6-ZigZag Conversion

LeetCode-6-ZigZag Conversion

str for neu lan etc 元素 mar out tput

算法描述:

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

解題思路:

對於這個題目,網上查了很久,終於找到一個比較好的解題思路。

以Example2為例,從P到I的距離為 2*numRows -2 = 6。也就是說每六個元素為一個循環,因此可以為6取模作為元素所在行的索引。其中,對於索引值小於numRows的直接用索引值作為行號,而大於等於的值則采用補數作為索引值。

    string convert(string s, int numRows) {
        if(numRows <=1) return s;
        string results;
        vector<string> str(numRows,"");
        for(int i =0; i < s.size(); i++){
            int index = i % (2*numRows -2);
            index = index < numRows? index : 2*numRows -2
- index; str[index] += s[i]; } for(int i=0; i < numRows; i++) results += str[i]; return results; }

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

LeetCode-6-ZigZag Conversion