LeetCode - Word Break
Posted IncredibleThings
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode - Word Break相关的知识,希望对你有一定的参考价值。
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: true Explanation: Return true because "leetcode" can be segmented as "leet code". Example 2: Input: s = "applepenapple", wordDict = ["apple", "pen"] Output: true Explanation: 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的主要内容,如果未能解决你的问题,请参考以下文章