Given the words table to find the words to meet the requirements

This part of a vocabulary for a given, and the target word, asking whether it can meet the corresponding requirements

  1. # 139. Word Break: by wordDict the word could constitute s
  2. # 140, Word Break2, returns the route
  3. # 127. Word Ladder, from beginWord to endWord, given wordList
  4. # 126, Word Ladder II, statistical path above the minimum number of steps
  5. # 472. Concatenated Words, words wordList find in other words consisting of
  6. # 1048. Longest String Chain, the list may be composed of a maximum length of string chain
  7. # 79. Word Search, a two-dimensional graph search letter word

# 139. Word Break: by wordDict in words can constitute s, with time out dfs

def wordBreak(s, wordDict):
    """
    :type s: str
    :type wordDict: List[str]
    :rtype: bool
    """
    length = len(s)
    if not wordDict and s:
        return False
    dp = [False for _ in range(length+1)]
    dp[0] = True
    minimum = min([len(i) for i in wordDict])
    for i in range(minimum,length+1):
        for j in wordDict:
            if i>=len(j):
                dp[i] = dp[i] or (dp[i-len(j)] and s[i-len(j):i]==j)
    return dp[-1]
wordBreak(s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"])

# 140, Word Break2, returns the route, but will encounter a case where no path TLE, # 139 can be retrieved to determine whether it is separable title

# With dp, dp remember each element of the path before the 
DEF wordBreak2 (S, wordDict):
     IF  Not wordDict and S:
         return [] 
    minLength = min (Map (len, wordDict)) 
    DP = [[] for _ in Range (len (S) + 1'd )] 
    DP [0] = [ "" ]
     for I in Range (minLength, len (S) + 1'd ):
         for Word in wordDict:
             IF len (Word) <= I:
                 IF S [I-len (Word): I] == Word andDP [I- len (Word)]: 
                    TEMP = [ELE + "  " + Word IF ! ELE = ""  the else ELE + Word for ELE in DP [I- len (Word)]] 
                    DP [I] + = TEMP
     return DP [-1 ]
 

# can also remember the path with the method of the DFS DEF wordBreak2 (S, wordDict): IF Not canBreak (S, wordDict): return [] length = len (S) ANS = [] DEF DFS (CUR, ANS , path): IF cur == length: ans.append(path[1:]) for word in wordDict: if len(word)<=length-cur and word==s[cur:cur+len(word)]: dfs(cur+len(word),ans,path+' '+word) dfs(0,ans,'') return ans

# 127. Word Ladder, from beginWord to endWord, given wordList, by wordList minimum number of steps, with bfs recording, steps can be simultaneously statistics

import collections
def ladderLength(beginWord, endWord, wordList):
    wordList = set(wordList)
    queue = collections.deque([[beginWord, 1]])
    while queue:
        word, length = queue.popleft()
        if word == endWord:
            return length
        for i in range(len(word)):
            for c in 'abcdefghijklmnopqrstuvwxyz':
                next_word = word[:i] + c + word[i+1:]
                if next_word in wordList:
                    wordList.remove(next_word)
                    queue.append([next_word, length + 1])
    return 0
ladderLength(beginWord = "hit",endWord = "cog",wordList = ["hot","dot","dog","lot","log","cog"])

# 126, Word Ladder II, statistical path above the minimum number of steps

def findLadders(beginWord, endWord, wordList):
    """
    :type beginWord: str
    :type endWord: str
    :type wordList: List[str]
    :rtype: List[List[str]]
    """
    if len(beginWord)!=len(endWord):
        return 0
    wordList = set(wordList)
    visited = set()
    level = {beginWord:[[beginWord]]}
    chars = [chr(i) for i in range(ord('a'),ord('z')+1)]
    while level:
        if endWord in level:
            return level[endWord]
        newlevel = dict()
        temp = set()
        for word in level:
            for i in range(len(word)):
                for char in chars:
                    newword = word[:i]+char+word[i+1:]
                    if newword in wordList and newword not in visited:
                        if newword not in newlevel:
                            newlevel[newword] = []
                        newlevel[newword]+=[j+[newword] for j in level[word]]
                        temp.add(newword)
        visited.update(temp)
        level = newlevel
    return []
findLadders(beginWord = "hit",endWord = "cog",wordList = ["hot","dot","dog","lot","log","cog"])

# 472. Concatenated Words, words wordList find in other words consisting of
# topic has been described a total of up to about 10K words, the total length does not exceed 600K, a description of each word length is relatively small, in this case, it is carried out the word segmentation, rather than go from the existing overlap in the word

# You can also create trie, and then look for dfs

def findAllConcatenatedWordsInADict(words):
    """
    :type words: List[str]
    :rtype: List[str]
    """
    words = set(words)
    res = []
    def dfs(word):
        for i in range(1,len(word)):
            prefix = word[:i]
            suffix = word[i:]
            if prefix in words and suffix in words:
                return True
            if prefix in words and dfs(suffix):#避免重复
                return True
        return False

    for i in words:
        if dfs(i):
            res.append(i)

    return res

# 1048. Longest String Chain, the list may be composed of a maximum length of string chain

  • Every attempt to do subtraction element, the element can be reduced if the found, the length +1
  • Requires the length from short to long, do ordering
def longestStrChain(words):
    """
    :type words: List[str]
    :rtype: int
    """
    chains = dict()
    words = sorted(words,key=len)
    for word in words:
        temp = 1
        for i in range(len(word)):
            newword = word[:i]+word[i+1:]
            if newword in chains:
                temp = max(temp,chains[newword]+1)
        chains[word] = temp
    return max(chains.values())
longestStrChain(["a","b","ba","bca","bda","bdca"])

# 79. Word Search, a two-dimensional graph search letter word

def existWord(board, word):
    if not board:
        return False
    directions = [[-1,0],[1,0],[0,-1],[0,1]]
    m,n = len(board),len(board[0])

    def dfs(i,j,k,visited=set()):
        if k==len(word)-1:
            return True
        k=k+1
        for direction in directions:
            x,y = i+direction[0],j+direction[1]
            if 0<=x<m and 0<=y<n:
                if (x,y) not in visited and board[x][y]==word[k]:
                    if dfs(x,y,k,visited|{(i,j)}):
                        return True
        return False

    for i in range(m):
        for j in range(n):
            if board[i][j]==word[0]:
                if dfs(i,j,k=0,visited=set()):
                    return True
    return False

 

Guess you like

Origin www.cnblogs.com/dl3182/p/11955845.html