Word Break, Leetcode 解题笔记

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

For example, given
s = “leetcode”,
dict = [“leet”, “code”].

Return true because “leetcode” can be segmented as “leet code”.

首先应该想到用dfs递归来解,如下:

public class Solution {
    public boolean wordBreak(String s, Set<String> dict) {
        return dfs(s, dict, 0);
    }
    public boolean dfs(String s, Set<String> dict, int start){
        if(start == s.length()) return true;
        for(int i = start+1; i <= s.length(); i++){
            String cur = s.substring(start, i);
            if(dict.contains(cur)){
                if(dfs(s, dict, i)){
                    return true;
                }
            }
        }
        return false;
    }
}

但是这样比较消耗时间,所以Leetcode上通不过。

最优解应该利用DP,定义possible[i] 为S字符串上[0,i]的子串是否可以被segmented by dictionary.

那么possible[i] = true if S[0,i]在dictionary里面

= true if possible[k] == true 并且 S[k+1,j]在dictionary里面

= false if no such k exist.

public class Solution {
    public boolean wordBreak(String s, Set<String> dict) {
        boolean[] dp = new boolean[s.length()+1];
        dp[0] = true;
        for(int i = 1; i < s.length()+1; i++){
            for(int j = 0; j < i; j++){
                if(dp[j] && dict.contains(s.substring(j, i))){
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[s.length()];
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s