zoukankan      html  css  js  c++  java
  • LeetCode -- Word Break

    Question:

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

    Analysis:

    给出一个字符串s和一个词典dict,判断s是否是由词典中词组成的一个字符串序列。

    思路:

    我们想知道整个句子是否是有词典中的词构成的,则很容易想到希望知道去掉最后一个字符构成的字符串是否满足条件,依次往前类推。这样很容易想到使用动态规划。

    如果某个位置i处是由词典中的词语构成的,并且从i处到j处又刚刚好构成一个词,这个词也在词典中出现,则j之前的所有字符串一定是满足条件的,

    因此状态转移方程为:

    dp[j] = dp[i] && dict.contains(s.subString(i, j));

    这样从开始处遍历整个字符串,得到整个dp数组。

    代码为:

    import java.util.Set;
    public class Solution {
        public boolean wordBreak(String s, Set<String> wordDict) {
            if(s == null || s.length() == 0) return false;
            int len = s.length();
            boolean[] dp = new boolean[len+1];
            dp[0] = true;
            for(int i=1; i<=len; i++) {
                for(int j=0; j<i; j++) {
                    if(dp[j] && wordDict.contains(s.substring(j, i))) {
                        dp[i] = true;
                        break;
                    }
                }
            }
            return dp[len];
        }
    }
  • 相关阅读:
    podupdate时没有进度
    IOS开发
    ios事件传递
    ioshittest的用法
    Ios中时间无法响应
    OS开发(Objective-C)常用库索引
    IOS时间戳
    iOS- 详解文本属性Attributes
    IOSView显示特性设置
    Xcode的Architectures和Valid Architectures的区别,
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/5391469.html
Copyright © 2011-2022 走看看