栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

单词拆分(字典数)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

单词拆分(字典数)

public class Trie {
    Trie[] children;
    boolean isEnd;

    public Trie() {
        children = new Trie[26];
        isEnd = false;
    }

    //插入
    public void insert(String word) {
        Trie node = this;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            int index = ch - 'a';
            if (node.children[index] == null) {
                node.children[index] = new Trie();
            }
            node = node.children[index];
        }
        node.isEnd = true;
    }

    //查询某个单词
    public boolean search(String word) {
        Trie node = searchPrefix(word);
        return node != null && node.isEnd;
    }

    //查询前缀是否存在
    public boolean startsWith(String prefix) {
        return searchPrefix(prefix) != null;
    }

    //查询前缀,并返回前缀
    private Trie searchPrefix(String prefix) {
        Trie node = this;
        for (int i = 0; i < prefix.length(); i++) {
            char ch = prefix.charAt(i);
            int index = ch - 'a';
            if (node.children[index] == null) {
                return null;
            }
            node = node.children[index];
        }
        return node;
    }
}

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main{
    static Trie trie=new Trie();
    static int[] failMemo=new int[301];
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        List list=new ArrayList<>();
        list.add("leet");
        list.add("code");
        System.out.println(wordBreak("leetcode",list));

    }
    public static boolean wordBreak(String s, List wordDict) {

        for (String string:wordDict
             ) {
            trie.insert(string);
        }
        return dfs(s,0);
    }
    public static boolean dfs(String s,int startPos){
        if (failMemo[startPos] == 1) return false;
        if (startPos == s.length()) return true;
        Trie trie1;
        trie1=trie;
        for (int i = startPos; i < s.length(); i++) {
            if (trie1.children[s.charAt(i)-'a']!=null)
            {
                trie1=trie1.children[s.charAt(i)-'a'];
                if (trie1.isEnd&&dfs(s,i+1))
                    return true;
            }
            else break;
        }
        failMemo[startPos]=1;
        return false;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/919571.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号