---
# System prepended metadata

title: 0271. Encode and Decode Strings
tags: [Leetcode, FaceBook, Medium]

---

# 0271. Encode and Decode Strings
###### tags: `Leetcode` `FaceBook` `Medium`
Link: https://leetcode.com/problems/encode-and-decode-strings/
## 思路
把每个字符串编译成 $[长度]/[字符串]$ 合并起来
注意：如果把第7行变成```sb.append(str.length()+'/')``` 字符串就会变成 52Hello52World 因为前面的str.length()是数字，后面的'/'也变成数字了
## Code
```java=
public class Codec {

    // Encodes a list of strings to a single string.
    public String encode(List<String> strs) {
        StringBuilder sb = new StringBuilder();
        for(String str:strs){
            sb.append(str.length()).append('/');
            sb.append(str);
        }
        return sb.toString();
    }

    // Decodes a single string to a list of strings.
    public List<String> decode(String s) {
        List<String> ans = new ArrayList<>();
        int idx = 0;
        while(idx<s.length()){
            int slash = s.indexOf('/',idx);
            int size = Integer.valueOf(s.substring(idx, slash));
            String str = s.substring(slash+1, slash+1+size);
            ans.add(str);
            idx = slash+1+size;
        }
        return ans;
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(strs));
```