LeetCode-6. ZigZag Conversion

题目连接

暴力O(n^2)

找规律O(n)

class Solution {
public:
    string convert(string s, int numRows) {
        
        if (numRows == 1) return s;
        
        string res = "";
        int all_step = (numRows - 1) * 2;
        int length = s.length();
        
        for (int i = 0; i < numRows; i++)
        {
            int index = i;
            int step = all_step - i * 2;
            if (step == 0) step = all_step;
            
            while(index < length)
            {
                res += s[index];
                index += step;
                step = all_step - step;
                if (step == 0) step = all_step;
            }
            
        }
        
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_30986521/article/details/80746069