Accepted C++ code


  • 0
    J

    For a string S, if the first character of it is a digit, then add it by 10 and set a flag to 'a', otherwise, do nothing to S, and set flag to 'b', generate encode string, encodeS, for it by length of S + S + flag.
    If S="abc", encodeS="3abcb"
    If S="1a2b", encodeS="4;a2ba"

    To decode it, first check prefix to get the length of each string, then check the flag to see if change the first character back to digit.

    class Codec {
    public:
    
        // Encodes a list of strings to a single string.
        string encode(vector<string>& strs) {
            string result="";
            for(auto s:strs){
                stringstream len;
                len<<s.length();
                result+=len.str();
                char f='a';
                if(s.length()>0 && isdigit(s[0]))
                    s[0]+=10;
                else 
                    f='b';
                result+=s;
                result.push_back(f);
            }
            return result;
        }
    
        // Decodes a single string to a list of strings.
        vector<string> decode(string s) {
            vector<string>result;
            int start=0,end=0;
            while (end<s.length()) {
                while (end<s.length() && isdigit(s[end]))
                    end++;
                int len=std::atoi(s.substr(start,end-start).c_str());
                string str=s.substr(end,len);
                if (len>0 && s[end+len]=='a')
                    str[0]-=10;
                result.push_back(str);
                end+=(len+1);
                start=end;
            }
            return result;
        }
    };

Log in to reply
 

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