標籤:div input size leetcode tco style bec 遍曆 節點
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.Note:The same word in the dictionary may be reused multiple times in the segmentation.You may assume the dictionary does not contain duplicate words.Example 1:Input: s = "leetcode", wordDict = ["leet", "code"]Output: trueExplanation: Return true because "leetcode" can be segmented as "leet code".Example 2:Input: s = "applepenapple", wordDict = ["apple", "pen"]Output: trueExplanation: Return true because "applepenapple" can be segmented as "apple pen apple". Note that you are allowed to reuse a dictionary word.Example 3:Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]Output: false
BFS需要一個隊列來實現。首先根據在dict中尋找s的首碼,如果有,排入佇列中,作為遍曆的“根”節點。比如上述的第二個例子,先入隊的有"car"和"ca"兩項;
當隊列不為空白時,隊頭top出列,令一個臨時字串temp是從s與top匹配後的字元開始到結束;如果此時temp是空,說明已經匹配完了,直接返回true,如果不為空白,則進一步在dict中尋找temp的首碼,如果有,排入佇列中。
當隊列為空白且沒有返回true時,說明匹配不成功,返回false。
按照這種做法,例子2首先入隊"car"和"ca",第一個出隊的是"car",temp是"s",在dict中尋找不到字串"s",就沒有新的字串入隊;下一個出隊的是"ca",那麼temp是"rs",在dict中找到"rs"入隊,下一步"rs"出隊後,temp是空,返回true。
class Solution { public boolean wordBreak(String s, List<String> wordDict) { if(s == null || s.length() == 0){ return false; } Queue<String> queue = new LinkedList<>(); int[] visitedLength = new int[s.length()+1]; for(int i = 0; i < wordDict.size(); i++){ if(s.indexOf(wordDict.get(i)) == 0){ queue.offer(wordDict.get(i)); visitedLength[wordDict.get(i).length()] = -1; } } while(!queue.isEmpty()){ String temp = queue.poll(); if(temp.length() == s.length()){ return true; } //temp always start from beginning of s String rest = s.substring(temp.length()); for(int i = 0; i < wordDict.size(); i++){ if(rest.indexOf(wordDict.get(i)) == 0 && visitedLength[(temp+wordDict.get(i)).length()] != -1){ queue.offer(temp+wordDict.get(i)); visitedLength[(temp+wordDict.get(i)).length()] = -1; } } } return false; }}
LeetCode - Word Break