Serialize and Deserialize Binary Tree 297/449/428

1. 297:   https://leetcode.com/articles/serialize-and-deserialize-binary-tree/

2. 449:   https://leetcode.com/problems/serialize-and-deserialize-bst/description/

3.  428:  https://leetcode.com/problems/serialize-and-deserialize-n-ary-tree/description/

4.271 是编解码 字符串数组:

   核心思想是选择正确的编码函数:  String.length + 分隔符(#) + string 来进行编码即可,程序比较简单。

public class Codec {

    // Encodes a list of strings to a single string.
    public String encode(List<String> strs) {
        
        StringBuilder res = new StringBuilder();
        for(String str: strs){

            res.append(str.length()+"#"+str);
        }
        //System.out.println(res);
        return res.toString();
        
    }

    // Decodes a single string to a list of strings.
    public List<String> decode(String s) {
        List<String> list = new ArrayList<>();
         String len = "";
     
        for(int i=0; i<s.length(); i++){
           
            if(s.charAt(i) == '#'){
                int lenth = Integer.valueOf(len);  
                list.add(s.substring(i+1, i+1+lenth));
                i += lenth;
                len = "";    
            }
            else {
                len += s.charAt(i);
            }
        }
       return list;   
    }
}

猜你喜欢

转载自www.cnblogs.com/keepAC/p/9880842.html