leetcode 271--自定义编码

2018-12-15  本文已影响0人  Ariana不会哭
图片.png
图片.png

题目给了一系列的字符串,让我们给它们加密,然后放在一个长字符串中:加密方法:
"abcd": 计算字符串长度+‘/’+字符串内容: “4/abcd”
C++:

// Encodes a list of strings to a single string.
string encode(vector<string>& strs) {
    string res = "";
    for (auto a : strs) {
        res.append(to_string(a.size())).append("/").append(a);
    }
    return res;
}
// Decodes a single string to a list of strings.
vector<string> decode(string s) {
    vector<string> res;
    while (!s.empty()) {
        int found = s.find("/");
        int len = atoi(s.substr(0, found).c_str());
        s = s.substr(found + 1);
        res.push_back(s.substr(0, len));
        s = s.substr(len);
    }
    return res;
}

JAVA:以下是自己的代码,但是速度不是很快。
原因:在循环中每次都更新字符串的内容,这样速度很慢

public class Codec {

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

    // Decodes a single string to a list of strings.
    public List<String> decode(String s) {
        List<String >ans= new ArrayList<String>();
        while(!s.isEmpty()){
            int idx=s.indexOf('-');
            int size=Integer.parseInt(s.substring(0, idx));
            //The substring begins at the specified beginIndex andextends to the character at index endIndex - 1
            ans.add(s.substring(idx+1,idx+size+1));
            s=s.substring(idx+size+1);
        }
        return ans;
    }
}

JAVA: 加快速度:使用下标来定位字符串位置:
以下是网上网友的答案:

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

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

猜你喜欢

热点阅读