2021-10-19

单词拆分

给定一个非空字符串 s 和一个包含非空单词的列表 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。

说明:

拆分时可以重复使用字典中的单词。
你可以假设字典中没有重复的单词。
示例 1:

输入: s = “leetcode”, wordDict = [“leet”, “code”]
输出: true
解释: 返回 true 因为 “leetcode” 可以被拆分成 “leet code”。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-break

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
在单词规模小的情况下其实可以对单词进行空格切分的枚举。
这个记忆化的一点是,分割左右两个子串的时候,左边的子串判断合法性时,以前是计算过的,可以直接取出来。
有一点重要的是,分割出来的两部分可以找到对应的单词,那么它们合并起来也是合法的。
感觉对这个题目理解还不够深刻。


class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        int n = s.length();
        boolean []dp = new boolean [n+1];
        Set<String> wordList = new HashSet(wordDict);
        dp[0]=true;//没想到是暴力枚举每一个子串啊,然后用哈希表进行判断子串是否存在。
        for(int i=1;i<=n;++i){
            for(int j=0;j<i;++j){
                if(dp[j]&&wordList.contains(s.substring(j,i))){
                    dp[i]=true;
                    break;
                }
            }
        }
        return dp[n];
    }
}

贴一个字典树的构建,今天再一次熟悉了它的插入和查找过程。

class Trie{
        public boolean isEnd;
        public Trie[] children;
        Trie(){
            this.isEnd=false;
            this.children=new Trie [26];
        }
        public void insert(String word){
            int n = word.length();
            Trie cur = this;
            for(int i =0;i<n;i++){
                char ch = word.charAt(i);
                int index=ch-'a';
                if(cur.children[index]==null){
                    cur.children[index]=new Trie();
                }
                cur=cur.children[index];
            }
            cur.isEnd=true;
        }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值