Leetcode 139 - Word Break

2018-06-15  本文已影响12人  BlueSkyBlue

题目:

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:

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的方法解决。


代码:

动态规划:

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;
    }
上一篇下一篇

猜你喜欢

热点阅读