当前位置:网站首页>Leetcode 6[finding rules] Z-transform the leetcode path of heroding

Leetcode 6[finding rules] Z-transform the leetcode path of heroding

2022-06-12 03:01:00 HERODING23

 Insert picture description here

Their thinking

A problem that can be solved by observing the law carefully , In fact, the string is not in accordance with N, But according to V Composed of , in other words , The minimum period is V type ,T by 2*numRows-2, In this way, the characters of each line can be found according to the periodic law , Further observation will reveal , For each V, Draw a horizontal line from top to bottom , There is only one dot except the first and last lines , The other positions are two points and symmetrical , So when we traverse , As long as it does not exceed the length of the string , For non first and last lines , And find out the symmetrical characters . The notes are already very detailed , The code is as follows :

Code

class Solution {
    
public:
    string convert(string s, int numRows) {
    
        int n = s.size();
        //  If it happens to be a row or a column 
        if(numRows == 1 || n <= numRows) {
    
            return s;
        }
        //  A cycle 
        int T = 2 * numRows - 2;
        string ans;
        //  Go through every line 
        for(int i = 0; i < numRows; i ++) {
    
            //  Traverse each cycle i Characters on line 
            for(int j = 0; j + i < n; j += T) {
    
                ans += s[i + j];
                //  Adjacent characters 
                if(i > 0 && i < numRows - 1 && j + T - i < n) {
    
                    ans += s[j + T - i];
                }
            }
        }
        return ans;
    }
};
原网站

版权声明
本文为[HERODING23]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203011114328922.html