Concise JAVA solution


  • 2

    The basic idea is referred from here: Encode string: length + '/' + string. And then decode it correspondingly, as the following:

    public class Codec {
        public String encode(List<String> strs) {
        	String res = "";
            for (String s: strs) 
            	res += String.format("%d/%s", s.length(), s);
            return res;
        }
    
        public List<String> decode(String s) {
            ArrayList<String> res = new ArrayList<String>();        
            int i = 0;
            while (i < s.length()) {
            	int slash = s.indexOf('/', i);
            	int length = Integer.valueOf( s.substring(i, slash) ); 
            	String one = s.substring(slash+1, slash+1+length);
            	res.add(one);
            	i = slash + 1 + length;
            }        	
            return res;
        }    
    }
    

  • 0
    H

    @Cheng_Zhang you really should use StringBuilder instead, Simply using String += "" is really slow.


Log in to reply
 

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