LeetCode(139)-Word Break(断字/动态规划)

题目:

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

翻译:

给定一个非空字符串s和一个包含非空单词列表的dictionary wordDict,确定是否可以将s分割为一个由一个或多个字典单词组成的空格分隔的序列。
注意:
同一词在词典中可以重复使用多次。
你可以假设字典里没有重复的单词。
示例1:
输入:s = “leetcode”, wordDict = [“leet”, “code”]
输出:true
说明:返回true,因为“leetcode”可以分割为“leetcode”。
示例2:
输入:s = “applepenapple”, wordDict = [“apple”, “pen”]
输出:true

思路:

本题使用动态规划,index是我们每次起始匹配字符串的角标,如果在wordDict集合中找到对应字符串,那么我们更新index的值,进行递归匹配。如果此角标匹配不成功,那么我们将其放入set集合,如果新的index在set集合中找到,那么该index肯定是匹配字符串不成功的。

代码:
class Solution {
    public boolean work(String s,List<String> wordDict,HashSet<Integer> set,int index){        //字符串匹配成功。
         if(index==s.length())
             return true;
             //set集合中包含此index,肯定匹配不成功,直接false
         if(set.contains(index))
             return false;
        //等于号,是因为subString()包含前不包含尾
        for(int i=index+1 ; i<=s.length() ; i++){
            //得到已index为头的所有子串。
            String sub=s.substring(index,i);
            //集合中是否包含此子串,如包含则得到新的index继续递归。
            if(wordDict.contains(sub)){
                if(work(s,wordDict,set,i)){
                    return true;
                }
                //接着匹配的也不成功,也将此坐标加入不成功集合
                set.add(i);
            }
        }
        set.add(index);
        return false;
   }
    public boolean wordBreak(String s, List<String> wordDict) {
        HashSet<Integer> set= new HashSet();
        return work(s,wordDict,set,0);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值