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

这道题真的很简单有没有,规律一找到直接5分钟就写完了- - 找规律20分钟吧。

 n = numRows

假设有 0 ~ (numRow-1)这么多行, 其实就是一个下标找规律,等差数列,不过分一分奇偶的情况

第 i 行,如果 i = 0 || i = (nRow - 1), 那么就是  a1 = i,  d = 2 * (numRow -1)

            其他行: a1 = i;   a(n) = a(n-1) + d;

                                    d = 2 * ( numRow - 1 - i)  ,如果 n 为奇数

                                    d = 2 * i ,如果 n 为偶数

AC 代码:( 0 和 numRows - 1的情况可以合起来,懒得改)

string convert(string s, int numRows) {
        if(numRows == 1)
            return s;
        int len;  int k = 0;
        len  = (int)s.length() - 1;
        
        string temp(s); //一样的长度的temp,这个算深拷贝吧- - 因为我怕有些编译器浅拷贝什么的
        for(int i = 0; i < numRows; i++){
            if( i == 0){
                int index = 0;
                while(index <= len){
                    temp[k++] = s[index];
                    index = index + 2*(numRows - 1);
                }
                continue;
            }
            if( i == numRows - 1){
                int index = numRows - 1;
                while(index <= len){
                    temp[k++] = s[index];
                    index = index + 2*(numRows - 1);
                }
                continue;
            }else{
                int index = i, flag = 0;
                while(index <= len){
                    temp[k++] = s[index];
                    if(flag == 0){
                        index = index + 2*(numRows - 1 - i);
                        flag = 1;
                    }else{
                        flag = 0;
                        index = index + 2 * i;
                    }
                }
            }
        }
        return temp;
    }



猜你喜欢

转载自blog.csdn.net/qq_25175067/article/details/80390213