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) {
        int len = s.length();
        if(len == 0){
            return false;
        }
        
        boolean f[] = new boolean[len];
        for(int i = 0; i<len; i++){
            for(int j = i; j>=0; j--){
                if((j==0 || f[j-1]) && dict.contains(s.substring(j, i+1))){
                    f[i] = true;
                    break;
                }
            }
        }
        
        return f[len-1];
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Given a non-empty string s and a dictionary wordDict cont...
    ShutLove阅读 4,241评论 0 2
  • 题目 Given a non-empty string s and a dictionary wordDict c...
    Leorio_c187阅读 1,579评论 0 0
  • 问题描述 Given a string s and a dictionary of words dict, det...
    codingXue阅读 2,656评论 0 0
  • 有的时候,我们总是爱幻想,幻想着自己能否像偶像剧或者小说里的主角那样。 优雅,知性举手投足都散发出不一样的气质。在...
    卷纸泡阅读 5,519评论 1 2
  • 每天用6秒,记录这一天中重要的行动和支出。这就是小6语记的口号。 6秒,在手机上可能一个全拼都还没打完。但小6可以...
    喵在野阅读 7,504评论 9 16