LeetCode-006:ZigZag Conversion

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32360995/article/details/86490976

题目:

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

题意:

给出一个字符串及行数,要求按照行数走“之字形”把字符串重新排列输出。

思路:

题意易懂,代码难写,难道要我利用二维数组模拟这一过程???太麻烦了吧~~~这其中定有奥秘emmm~让我们来找啊找啊找规律(根据字符串下标index、行数n):

n=2时的走法是:

 0 2 4 6

 1 3 5 7

 n=3时的走法是:

 0     4     8

 1  3 5  7 9

 2     6    10

 n=4时的走法是:

 0      6        12

 1   5 7    11 13

 2 4   8 10    14

 3      9         15


蓝色数字的部分我们可以发现相邻两列的差为2*n-2;红色数字就比较有难度了,红色数字下标为j+2*n-2-2*i(j为当前列的下标,i为当前行的下标);红色数字只在非首尾两行出现~

参考了这位小姐姐的思路,反正红色数字的规律我是很懵逼的,附上链接http://www.cnblogs.com/springfor/p/3889414.html

Code:

class Solution {
public:
    string convert(string s, int numRows) {
        if(numRows==1) return s;
        string str="";
        int size=2*numRows-2,len=s.length();
        for(int i=0;i<numRows;i++){
            for(int j=i;j<len;j+=size){
                str+=s[j];
                if(i&&i!=numRows-1){
                    int t=j+size-2*i;
                    if(t<len) str+=s[t];
                }
            }
        }
        return str;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_32360995/article/details/86490976