9 ms , Java, Kind like command frames in hardware system


  • 0
    Q

    Encode by adding a length in front of each string,
    Decode by substring the message according to the length

    public class Codec {
        // Encodes a list of strings to a single string.
        public String encode(List<String> strs) {
            StringBuilder sb = new StringBuilder();
            for(String s : strs){
                sb.append(s.length());
                sb.append(' ');
                sb.append(s);
            }
            // do your encryption here if you want.
            return sb.toString();
        }
    
        // Decodes a single string to a list of strings.
        public List<String> decode(String s) {
            List<String> result = new ArrayList<String>();
            int len = 0;
            for(int i = 0; i < s.length(); ++i){
                char tc = s.charAt(i);  
                if(tc != ' '){
                    len*=10;
                    len+=tc-'0';
                }
                else{
                    result.add(s.substring(i+1,i+1+len)); 
                    i = i + len;
                    len = 0;                
                }
            }
            return result;
        }
    }

Log in to reply
 

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