美文网首页
Leetcode 139 - Word Break

Leetcode 139 - Word Break

作者: BlueSkyBlue | 来源:发表于2018-06-15 18:11 被阅读12次

    题目:

    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.

    Example1:

    Input: s = "leetcode", wordDict = ["leet", "code"]
    Output: true
    Explanation:Return true because "leetcode" can be segmented as "leet code".

    Example2:

    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.

    Example3:

    Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
    Output: false


    思路:

    这道题可以采用动态规划的思想来解决。

    首先是状态数组dp[i]代表s中从第一个字符到第i个字符所组成的字符串是否能被字典中的字符所切割。

    之后是状态方程,假设0 ~ j 中 0 ~ i 个字符已经确定在字典中,则需要检查i+1 ~ j所组成的字符串是否包含在字典中。如果包含则dp[i]为true。

    最后返回dp[s的长度],代表着s字符是否会被字典中的字符串所切割。

    除此之外,这道题也可以使用BFS的方法解决。

    • 首先定义队列queue和访问数组visit
    • 将第0个位置加入到queuevisit中。
    • queue中的元素弹出查找之后可被切割的字符的位置加入到queue中,同时将访问数组visit标记为被访问。
    • 一旦查找到的位置刚好等于给定字符串的长度并且可被字典中的字符切割则返回true

    代码:

    动态规划:

    public boolean wordBreak(String s, List<String> wordDict) {
            boolean result = false;
            int [] dp = new int [s.length() + 1];
            dp[0] = 1;
            for(int i=1;i<s.length() + 1;i++){
                for(int j=0;j<i;j++){
                    String substr = s.substring(j, i);
                    if(dp[j] == 1 && wordDict.contains(substr)){
                        dp[i] = 1;
                        break;
                    }
                }
            }
            return dp[s.length()] == 1;
        }
    

    BFS:

    public boolean wordBreak(String s, List<String> wordDict) {
            Queue<Integer>queue = new LinkedList<Integer>();
            queue.offer(0);
            boolean [] visit = new boolean [s.length() + 1];
            visit[0] = true;
            while(!queue.isEmpty()){
                int cur = queue.poll();
                for(int i = cur+1;i<=s.length();i++){
                    if(!visit[i] && wordDict.contains(s.substring(cur, i))){
                        if(i == s.length())
                            return true;
                        queue.add(i);
                        visit[i] = true;
                    }
                }
            }
            return false;
        }
    

    相关文章

      网友评论

          本文标题:Leetcode 139 - Word Break

          本文链接:https://www.haomeiwen.com/subject/avimeftx.html