【leetcode】648. 单词替换

【leetcode】648. 单词替换_第1张图片

暴力解法超出了时间限制。

要用到字典树(之后再学习。。。)

ac的答案:(和超出内存限制的思路一样)

root_dict = set(dict)
raws = sentence.split()
res = []
for raw in raws:
    flag = False
    for i in range(0, len(raw)):
        prefix = raw[0:i + 1]
        if prefix in root_dict:
            res.append(prefix)
            flag = True
            break
    if flag == False:
        res.append(raw)
return ' '.join(res)

class Solution(object):
    def replaceWords(self, dict, sentence):
        """
        :type dict: List[str]
        :type sentence: str
        :rtype: str
        """
        myDict = {}
        res = ""
        for word in dict:
            if word in myDict:
                myDict[word]+=1
            else:
                myDict[word]=1
        # print(myDict)

        for word in sentence.split(): # 字符串按空格划分
            cur_word = ""
            for i,ch in enumerate(word):
                cur_word += ch
                if cur_word in myDict:
                    if res == "":
                        res += cur_word
                    else:res += ' '+cur_word
                    break
                if i==len(word)-1:
                    if res == "":
                        res+=word
                    else:
                        res += ' '+word
        return res

然后,res由字符串变为列表就不内存溢出了

myDict = set(dict) # 这里按照上述生成字典的方式,也ac
res = []  # res由字符串变为列表就不内存溢出了
for word in sentence.split(): # 字符串按空格划分
    cur_word = ""
    for i,ch in enumerate(word):
        cur_word += ch
        if cur_word in myDict:
            res.append(cur_word)
            break
        if i==len(word)-1:
            res.append(word)
return " ".join(res)

 

你可能感兴趣的:(leetcode)