word-break Java code

来源:互联网 发布:mysql 客户端查询乱码 编辑:程序博客网 时间:2024/06/04 23:48

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<String> dict) {        if (dict.size()==0||s.length()==0) {                return false;            }            int len = s.length();            Boolean[] dp = new Boolean[len+1];            dp[0] = true;            //记录以XX结尾的字符串是否可分,动态规划            for (int i = 1; i < s.length()+1; i++) {                for (int j = i-1; j >= 0; j--) {                    if (dp[j]&&dict.contains(s.substring(j,i))) {                        dp[i] = true;                        break;                    }else {                        dp[i] = false;                    }                }            }            return dp[len];    }}