Java Solution | 33 ms


  • 0
    S
    public class Codec {
    
        // Encodes a list of strings to a single string.
        public String encode(List<String> strs) {
            
            StringBuffer sb = new StringBuffer();
            String encode = "%%";
        
            for(int i=0; i < strs.size(); i++){
                
                int size = strs.get(i).length();
                
                sb.append(encode);
                sb.append(size);
                sb.append(encode);
                sb.append(strs.get(i));
            }
            return sb.toString();
        }
    
        // Decodes a single string to a list of strings.
        public List<String> decode(String s) {
            
            List<String> list = new ArrayList<String>();
            int i=0;
            while(i < s.length()){
                
                if(s.charAt(i) == '%' && s.charAt(i+1) == '%')
                    {
                        i = i+2;
                        int sum =0;
                        
                        while(s.charAt(i) >= '0' && s.charAt(i) <= '9'){
                            
                            sum = 10 * sum + Character.getNumericValue(s.charAt(i));
                            i++;                        
                        }
                        i =  i +2;
                        int k =0;
                         StringBuffer sb = new StringBuffer();
                        while(k < sum){
                         sb.append(s.charAt(i));
                         i++;
                         k++;
                        }
                        list.add(sb.toString());
                    }
            }
        
            return list;
        }
    }
    
    // Your Codec object will be instantiated and called as such:
    // Codec codec = new Codec();
    // codec.decode(codec.encode(strs));

Log in to reply
 

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