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

 

相关文章:

  • 2022-01-15
  • 2021-10-28
  • 2021-04-06
  • 2021-06-03
  • 2021-07-29
  • 2021-06-24
  • 2022-01-30
猜你喜欢
  • 2021-10-17
  • 2021-11-02
  • 2021-07-15
  • 2022-12-23
  • 2021-11-07
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案