Run length encoding simple C++


  • 0
    H

    I am not sure why it shows "output limit" ? When I tested my code offline, it works well.

    Here is an example :

    vector < string > strs;
    strs.push_back("fffffffff");
    strs.push_back("bbbb");
    strs.push_back("ttttttt");
    strs.push_back("pppp");
    strs.push_back("y");
    strs.push_back("k");

    The output of encode should be : 9@f4@b7@t4@p1@y1@k

    Then decode function will restore it back;

    string encode(vector < string > & strs) {

           string res = "";
           int n = strs.size();
           if(n==0) return res;
    
        for(int i=0; i<n; i++){
            
            string cur = strs[i];
            int p=0;
    
            while(p<cur.length()){
    
                 int cnt = 1;
                 while(p<cur.length() && cur[p+1] == cur[p]){
                     p++;
                     cnt++;
                 }
                 res += to_string(cnt) + "@" + cur[p];
                 p++;
            }
        }
        
        return res;
    

    }

    // Decodes a single string to a list of strings.
    vector<string> decode(string s) {
        
         int n = s.length();
         vector<string> res;
         if(n==0) return res;
         int i=0;
         
         while(i<n){
             
             int pos = s.find_first_of('@',i);
             int cnt = stoi(s.substr(i,pos-i+1));
             char c = s[pos+1];
             string cur = "";
             
             for(int m=0; m<cnt; m++){
               cur += c;
             }
        
            res.push_back(cur);
          
            i = pos+2;
         }
        
      return res;
      
    }

  • 0
    K

    could be wrong:
    'for(int m=0; m<cnt; m++){
    cur += c;
    }
    '


  • 0
    H

    Many thanks. Could you please let me know how should i modify it , if possible ?


Log in to reply
 

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