Is vector<string> not accpetable in c++? Always got TE. Here's my matrix solvement.


  • 0
    L

    I tried to use vector<string> res(nRows, "") to store the transition state but always got a TE when input was ["AB", 2].

    So I made a change using vector<vector<char> > res instead. This is "awful" because I had to append every char to the final result.

    Alg is simple, just use direction changing.

    class Solution {
    public:
        string convert(string s, int nRows) {
            if (s.length() <= nRows || nRows == 1) return s;
            
            vector<vector<char> > res(nRows);
            int row = 0, dir = 1;
            for (string::iterator it = s.begin(); it != s.end(); ++it) {
                res[row].push_back(*it);
                row += dir;
                if (dir == 1 && row == nRows-1) dir = -1;
                else if (dir == -1 && row == 0) dir = 1;
            }
            string result = "";
            for (vector<vector<char> >::iterator it = res.begin(); it != res.end(); ++it) {
                string temp = "";
                for (vector<char>::iterator iit = (*it).begin(); iit != (*it).end(); ++iit)
                    temp += (*iit);
                result.append(temp);
            }
            return result;
        }
    };

  • 0
    T

    I use vector<string> and accepted.Your failed solution must have a dead loop, check your iterator.


Log in to reply
 

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