Mathematical Solution


  • 0
    A

    If you label the index next to the characters in the sample, you can easily find some pattern, that's it.

    class Solution {
    public:
        string convert(string s, int numRows) {
            vector<string> str(numRows);
            int count = numRows * 2 - 2;
            if (count == 0) count = 1;
            int a = count;
            for(int i = 0; i < numRows; i++) {
                string &tmp = str[i];
                int index = i, step = a;
                while(index < s.length()) {
                    tmp.push_back(s[index]);
                    index += step;
                    if (step == 0) index += count;
                    step = count - step;
                }
                a -= 2;
            }
            string ans;
            for(string &tmp : str) ans += tmp;
            return ans;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.