美文网首页
单词中断(LeetCode==>Word Break)

单词中断(LeetCode==>Word Break)

作者: Katakuly | 来源:发表于2018-09-01 22:12 被阅读0次

    题目描述:给定非空字符串s和包含非空单词列表的字典wordDict,确定是否可以将s分割为一个或多个字典中所包含的单词序列(通过空格区分)。
    说明:
    1.词典中的同一个词可以在分割中重复使用多次

    1. 你可以假设字典不包含重复的单词
      Example1:
    Input: s = "leetcode", wordDict = ["leet", "code"]
    Output: true
    Explanation: Return true because "leetcode" can be segmented as "leet code".
    

    Example2:

    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.
    

    Example3:

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

    通过函数递归调用判断是否包含:

    class Solution {
        Set<String> set=new HashSet<>();
        public boolean wordBreak(String s, List<String> wordDict) {
            if(wordDict.contains(s))
                return true;
            if(set.contains(s))
                return false;
            for(String string:wordDict){
                if(s.startsWith(string)){
                    if(wordBreak(s.substring(string.length()),wordDict))
                        return true;
                }
            }
            set.add(s);
            return false;
        }
    }
    

    相关文章

      网友评论

          本文标题:单词中断(LeetCode==>Word Break)

          本文链接:https://www.haomeiwen.com/subject/uyzuwftx.html