Accepted C++ solution with bit manupulation


  • 0
    J
    // Encodes a list of strings to a single string.
    string encode(vector<string>& strs) {
    	string s;
    	for (int i = 0; i<strs.size(); i++) {
    		int len = strs[i].length();
    		char n1 = len & 0xFF000000;
    		char n2 = len & 0x00FF0000;
    		char n3 = len & 0x0000FF00;
    		char n4 = len & 0x000000FF;
    
    		s += string(1, n1) + string(1, n2) + string(1, n3) + string(1, n4) + strs[i];
    	}
    
    	return s;
    }
    
    // Decodes a single string to a list of strings.
    vector<string> decode(string s) {
    	vector<string> strs;
    	int pos = 0;
    
    	while (pos < s.length()) {
    		char n1 = s[pos++];
    		char n2 = s[pos++];
    		char n3 = s[pos++];
    		char n4 = s[pos++];
    
    		int len = 0;
    		len |= n4;			len &= 0x000000FF;
    		len |= n3 << 8;		len &= 0x0000FFFF;
    		len |= n2 << 16;	len &= 0x00FFFFFF;
    		len |= n1 << 24;	len &= 0xFFFFFFFF;
    
    		strs.push_back(s.substr(pos, len));
    		pos += len;
    	}
    
    	return strs;
    }

  • 0

    Got a bug, forgot to shift during encoding.


Log in to reply
 

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