Sunday, January 11, 2015

LeetCode 139: Word Break

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".
public class Solution {
    public boolean wordBreak(String s, Set<String> dict) {
        // DP problem
        // If t[i] is true, it represents that the substring (from 0 to i-1) of 's' can be segmented by 'dict'. 
        boolean[] t = new boolean[s.length()+1];
        
        // Initial state: t[0] = true
        t[0] = true;
 
        for(int i=0; i<s.length(); i++)
        {
            // Start form the next match position
            if (!t[i])
                continue;
 
            for (String a : dict)
            {
                int len = a.length();
                int end = i + len;
                
                // Overflow, match is not possible
                if (end > s.length())
                    continue;
                    
                // If already matched at the 'end' position, pass the verification.
                if (t[end])
                    continue;
                
                // If matched, mark the 'end' position.
                // Mark all of the matched 'end' positions.
                if (s.substring(i, end).equals(a))
                    t[end] = true;
            }
        }
 
        return t[s.length()];
    }
}

No comments:

Post a Comment