20200319-leetcode-820. 单词的压缩编码(后缀匹配)

在这里插入图片描述
传送

其实要排除列表中后缀相重合的字符,开始直接匹配后缀是否重合,超时了。
思路是先把单词反转过来,就变成了匹配前缀了,但是这样需要遍历两遍,那么不妨先排序,然后只需要比较相邻的两个字母。

class Solution(object):
    def minimumLengthEncoding(self, words):
        """
        :type words: List[str]
        :rtype: int
        """
        reverseWord = []
        for word in set(words):
            reverseWord.append(word[::-1])

        reverseWord.sort()
        cur = ""
        num = 0
        for word in reverseWord + [""]:
            if not word.startswith(cur):
                num = num + len(cur) + 1
            cur = word

        return num

开始写的代码超时了,思路如下:

class Solution {
public:
    int minimumLengthEncoding(vector<string>& words) {
        string s=words[0];
        int num=s.length();
        int len=words.size();
        if(len==1) return num+1;

        vector<string> res;
        int book[3000];
        memset(book,0,sizeof(book));

        for(int i=0;i<len;i++){
            bool flag=true;
            for(int j=0;j<len;j++){
                if(book[j]==1) continue;
                if(i==j) continue;
                int idx=words[j].find(words[i]);
                int idx2=words[i].find(words[j]);

                int len1=words[i].length();
                int len2=words[j].length();

                if(idx2!=string::npos&&idx2==len1-len2){
                    book[j]=1;
                }

                if(idx!=string::npos&&idx==len2-len1){         //找到后缀了
                    flag=false;
                    book[i]=1;
                    break;
                }
            }
            if(flag) {res.push_back(words[i]);}
        }
        int sum=0;
        for(int i=0;i<res.size();i++)
        {
            sum=res[i].size()+1+sum;
        }
        return sum;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值