zoukankan      html  css  js  c++  java
  • 43.Word Break(看字符串是否由词典中的单词组成)

    Level:

      Medium

    题目描述:

    Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

    Note:

    • The same word in the dictionary may be reused multiple times in the segmentation.
    • You may assume the dictionary does not contain duplicate words.

    Example 1:

    Input: s = "leetcode", wordDict = ["leet", "code"]
    Output: true
    Explanation: Return true because "leetcode" can be segmented as "leet code".
    

    Example 2:

    Input: s = "applepenapple", wordDict = ["apple", "pen"]
    Output: true
    Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
                 Note that you are allowed to reuse a dictionary word.
    

    Example 3:

    Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
    Output: false
    

    思路分析:

      题目要求判断给出的字符串是否能由词典中的单词组成,我们应该用动态规划的思想去解决。但凡是能把问题规模缩小的都应该想到用动态规划求解。例如本题,如果我知道给定字符串的0到i子串可以用字典中的单词表达,那么我只需要知道i+1到末尾的子串能否被字典表达即可知道整个字符串能否被字典表达。所以随着i的增大,问题规模逐渐的缩小,且之前求解过的结果可以为接下来的求解提供帮助,这就是动态规划了。设dp[i]代表s.substring(0, i)能否被字典表达,此刻我们知道dp[0]~dp[i-1]的结果。而dp[i]的结果由两部分组成,一部分是dp[j](j < i),已知;另一部分是j到i之间的字符串是不是在字典里。当这两个部分都为真的时候,dp[i]即为真。而一旦dp[i]为真,就不用继续迭代了。测试的时候发现倒着遍历会比正着遍历速度稍稍快一点,大概是因为test case的字典里长度较长的单词要比长度较短的单词多。

    代码:

    public class Solution{
        public boolean wordBreak(String s,List<String>wordDict){
            if(s==null||s.length()==0)
                return false;
            boolean []dp=new boolean [s.length()+1]; //dp[i]表示字符串的前i个字符是否能由词典中的单词表示。
            dp[0]=true;
            for(int i=1;i<=s.length();i++){
                for(int j=0;j<i;j++){
                    if(dp[j]&&wordDict.contains(s.substring(j,i))){
                        dp[i]=true;
                        break;
                    }
                }
            }
            return dp[s.length()];
        }
    }
    
  • 相关阅读:
    JMeter设置中文界面显示
    Linux搭建JAVA环境
    SQLyog连接MySQL时出现错误代号:2058
    SQL基础教程(第2版)笔记整理
    sqlserver查询数据的所有表名和行数
    【ASP.NET 问题】IIS发布网站后出现 "处理程序“PageHandlerFactory-Integrated”在其模块列表中有一个错误"的解决办法
    Asp.net在IE10、IE11下事件丢失经验总结
    SQL 2008 R2下载 升级R2 SP1或者SQL 2008从10.50.1600升级10.5.2500
    IE9浏览器中的My97日历控件刷新后无法打开问题解决办法
    windows2008 c盘清理
  • 原文地址:https://www.cnblogs.com/yjxyy/p/11080217.html
Copyright © 2011-2022 走看看