C++ solution based f(x) = |x| function


  • 0
    X

    combine moving f(x) and modulo x,we can get a formula that indicate which line the character in.it looks like line(x) = |(x mod T) - k|.
    in this problem k = numRows - 1, T = 2k, corresponding to code
    "auto line = [&](int i)->int{return abs((i % (2 *(numRows - 1))) - numRows + 1);};"

    class Solution {
    public:
        string convert(string s, int numRows) {
            const int sz = s.size();
            if(sz < 3 || numRows <= 1) return s;
            const char *c = s.data();
            vector<vector<char>> lines(numRows);
            //calculate line index for character
            auto line = [&](int i)->int{return abs((i % (2 *(numRows - 1))) - numRows + 1);};
            //for each character
            for(int i = 0; i < sz; ++i)
                lines[line(i)].push_back(c[i]);
            string ret;
            //concat each line
            for(auto it = lines.rbegin(); it != lines.rend(); ++it)
                ret += string(it->begin(),it->end());
            return ret;
        }
    };
    

Log in to reply
 

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