194. 寻找单词

194. 寻找单词

中文 English

给定一个字符串str,和一个字典dict,你需要找出字典里的哪些单词是字符串的子序列,返回这些单词。

样例

例1:

输入:
str="bcogtadsjofisdhklasdj"
dict=["book","code","tag"]
输出:
["book"]
解释:只有book是str的子序列

例2:

输入:
str="nmownhiterer"
dict=["nowhere","monitor","moniter"]
输出:
["nowhere","moniter"]

挑战

|str|<=100000

注意事项

  1. |str|<=1000
    2.字典中所有单词长度的总和<=1000
    (题目保证所有字母均为小写)
 
输入测试数据 (每行一个参数) 如何理解测试数据?
class Solution:
    """
    @param str: the string
    @param dict: the dictionary
    @return: return words which  are subsequences of the string
    """
    '''
    大致思路:
    1.初始化res =[],循环dict,判断各个单词是否按顺序出现str中,如果是append到res
    '''
    def findWords(self, str, dict):
        res = []
        for s in dict:
            if self.IsExist(s,str) == True:
                res.append(s)
        return res
    
    def IsExist(self,s,str):
        for i in s:
            if i not in str :
                return False
            index = str.index(i)
            str = str[index+1:]
        return True

猜你喜欢

转载自www.cnblogs.com/yunxintryyoubest/p/12920695.html