leetcode 648

这题思路很简单,首先要把句子分成一个个词,然后看词的前面是不是有和root相同的,取最小的那个替换就好。discuss答案太秀,我觉得没有啥学习的必要。附代码:

class Solution:
    def replaceWords(self, dict, sentence):
        """
        :type dict: List[str]
        :type sentence: str
        :rtype: str
        """
        sen = sentence.split()
        result = ""
        for val in sen:
            minLen = 10000
            tempRoot = val
            for root in dict:
                temp = val[0:len(root)]
                if temp == root:
                    if len(root) < minLen:
                        tempRoot = root
                        minLen = len(root)
            result = result + tempRoot + " "
        result = result[0:len(result)-1]
        return result

你可能感兴趣的:(leetcode)