LeetCode--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".

import java.util.*;
public class Solution {
    public boolean wordBreak(String s, Set dict) {
        boolean dp[] = new boolean[s.length()+1];
        dp[s.length()] =true;
        if(s == null || dict == null){
            return false;
        }
        for(int i = s.length()-1;i>=0;i--){
            for(int j = i;j < s.length();j++){
                if(dict.contains(s.substring(i,j+1)) && dp[j+1]){
                    dp[i] = true;
                }
            }
        }
        return dp[0];
    }
}

你可能感兴趣的:(leetcode经典编程题)