Java - length plus a dilimiter in the header.


  • 1
    J

    public class Codec {

    public String encode(List<String> strs) {
    	StringBuffer ans = new StringBuffer();
    	for (String s : strs) {
    		ans.append(s.length()).append("#").append(s).append("#");
    	}
        return ans.toString();
    }
    
    public List<String> decode(String s) {
        List<String> ans = new ArrayList<>();
        int i = 0, start = 0;
        while (start < s.length() && (i = s.indexOf("#", start)) != -1) {
        	int len = Integer.parseInt(s.substring(start, i));
        	i++;
        	String str = s.substring(i, i + len);
        	ans.add(str);
        	start = i + len + 1;
        }
        return ans;
     }
    

    }


Log in to reply
 

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