单词分割匹配字典

问题

给定一个字符串s和一个单词字典dict,确定s是否可以被分割成一个或多个字典单词的空格分隔序列。例如,给定s =“leetcode”, dict = [“leet”, “code”]。返回true,因为"leetcode"可以被分割为“leet code”。

解决方案

1. 朴素方法

这个问题可以通过使用一种简单的方法来解决。讨论总是可以从这开始。

public static boolean wordBreak1(String s, Set<String> dict) {
    return wordBreak1(s, dict, 0);
}

// 参数start指的是字符串的字符索引
public static boolean wordBreak1(String s, Set<String> dict, int start) {
    // 分割到末尾 视为成功
    if (start == s.length()) {
        return true;
    }
    // 遍历字典
    for (String a : dict) {
        int len = a.length();
        int end = len + start;
        if (end > s.length()) {
            continue;
        }
        if (s.substring(start, start + len).equals(a)) {
            // 对剩余的子串进行字典匹配
            if (wordBreak1(s, dict, start + len)) {
                return true;
            }
        }
    }
    return false;
}

时间:O (n2),此解决方案超出时间限制。

2. 动态规划法

采用动态规划方法解决该问题的关键是:

  • 定义一个数组t[],使t[i]==true =>0-(i-1)可以使用字典进行分段;
  • 初始状态 t[0]==true;
public static boolean wordBreak2(String s, Set<String> dict) {
    boolean[] t = new boolean[s.length() + 1];
    t[0] = true;

    for (int i = 0; i < s.length(); i++) {
        if (!t[i]) {
            continue;
        }
        // 只有t[i]=true时继续往下匹配 否则跳过
        for (String a : dict) {
            int len = a.length();
            int end = i + len;
            if (end > s.length()) {
                continue;
            }
            if (t[end]) {
                continue;
            }
            if (s.substring(i, end).equals(a)) {
                t[end] = true;
            }
        }
    }
    return t[s.length()];
}

时间:O(字符串长度*字典大小)

这个解决方案中一个棘手的部分是:我们应该找到所有可能的匹配,而不是停留在“程序目标”。

3. 正则表达式

这个问题应该等同于匹配正则表达式 (leet|code)*,这意味着它可以通过在O(2^m)中构建一个DFA并在O(n)中执行来解决。Leetcode在线评判不允许使用Pattern类。

public static void main(String[] args) {
    String s = "leetcode";
    Set<String> dict = new HashSet<>();
    dict.add("leets");
    dict.add("leet");
    dict.add("code");

    StringBuilder sb = new StringBuilder();
    for (String str : dict) {
        sb.append(str + "|");
    }
    String pattern = sb.toString().substring(0, sb.length() - 1);
    pattern = "(" + pattern + ")*";
    Pattern p = Pattern.compile(pattern);
    // 正则表达式 (leets|leet|code)*
    Matcher m = p.matcher("leetcode");
    boolean matches = m.matches();
    if (m.matches()) {
        System.out.println("true");
    }
}

问题

给定一个字符串s和一个单词字典dict,确定s是否可以被分割成一个或多个字典单词的空格分隔序列。例如,给定s =“leetcode”, dict = [“leet”, “code”]。返回true,因为"leetcode"可以被分割为“leet code”。

解决方案

1. 朴素方法

这个问题可以通过使用一种简单的方法来解决。讨论总是可以从这开始。

public static boolean wordBreak1(String s, Set<String> dict) {
    return wordBreak1(s, dict, 0);
}

// 参数start指的是字符串的字符索引
public static boolean wordBreak1(String s, Set<String> dict, int start) {
    // 分割到末尾 视为成功
    if (start == s.length()) {
        return true;
    }
    // 遍历字典
    for (String a : dict) {
        int len = a.length();
        int end = len + start;
        if (end > s.length()) {
            continue;
        }
        if (s.substring(start, start + len).equals(a)) {
            // 对剩余的子串进行字典匹配
            if (wordBreak1(s, dict, start + len)) {
                return true;
            }
        }
    }
    return false;
}

时间:O (n2),此解决方案超出时间限制。

2. 动态规划法

采用动态规划方法解决该问题的关键是:

  • 定义一个数组t[],使t[i]==true =>0-(i-1)可以使用字典进行分段;
  • 初始状态 t[0]==true;
public static boolean wordBreak2(String s, Set<String> dict) {
    boolean[] t = new boolean[s.length() + 1];
    t[0] = true;

    for (int i = 0; i < s.length(); i++) {
        if (!t[i]) {
            continue;
        }
        // 只有t[i]=true时继续往下匹配 否则跳过
        for (String a : dict) {
            int len = a.length();
            int end = i + len;
            if (end > s.length()) {
                continue;
            }
            if (t[end]) {
                continue;
            }
            if (s.substring(i, end).equals(a)) {
                t[end] = true;
            }
        }
    }
    return t[s.length()];
}

时间:O(字符串长度*字典大小)

这个解决方案中一个棘手的部分是:我们应该找到所有可能的匹配,而不是停留在“程序目标”。

3. 正则表达式

这个问题应该等同于匹配正则表达式 (leet|code)*,这意味着它可以通过在O(2^m)中构建一个DFA并在O(n)中执行来解决。Leetcode在线评判不允许使用Pattern类。

public static void main(String[] args) {
    String s = "leetcode";
    Set<String> dict = new HashSet<>();
    dict.add("leets");
    dict.add("leet");
    dict.add("code");

    StringBuilder sb = new StringBuilder();
    for (String str : dict) {
        sb.append(str + "|");
    }
    String pattern = sb.toString().substring(0, sb.length() - 1);
    pattern = "(" + pattern + ")*";
    Pattern p = Pattern.compile(pattern);
    // 正则表达式 (leets|leet|code)*
    Matcher m = p.matcher("leetcode");
    boolean matches = m.matches();
    if (m.matches()) {
        System.out.println("true");
    }
}

对上面问题的进行引申,抛出一个新的问题。

问题

给定一个字符串s和一个单词字典dict,在s中添加空格来构造一个句子,其中每个单词都是字典中的有效单词,返回所有这些可能的句子。

例如,给定s = “catsanddog”, dict = [“cat”, “cats”, “and”, “sand”, “dog”],解决方案是[“cats anddog”, “catsanddog”]。

解决方案

1. 动态规划法

这个问题与上面的单词分割非常相似。我们需要跟踪实际的单词,而不是使用布尔数组(上面的单词分割)来跟踪匹配位置。然后,我们可以使用深度优先搜索来获取所有可能的路径,即字符串列表。

下图显示了跟踪阵列的结构:

在这里插入图片描述

public static List<String> wordBreak(String s, Set<String> dict) {
        List<String> dp[] = new ArrayList[s.length() + 1];
        dp[0] = new ArrayList<>();

        for (int i = 0; i < s.length(); i++) {
            if (dp[i] == null) {
                continue;
            }

            for (String word : dict) {
                int len = word.length();
                int end = len + i;
                if (end > s.length()) {
                    continue;
                }
                if (s.substring(i, end).equals(word)) {
                    if (dp[end] == null) {
                        dp[end] = new ArrayList<String>();
                    }
                    dp[end].add(word);
                }
            }
        }
        List<String> result = new LinkedList<>();
        if (dp[s.length()] == null) {
            return result;
        }
        ArrayList<String> temp = new ArrayList<>();
        dfs(dp, s.length(), result, temp);

        return result;
    }

    public static void dfs(List<String> dp[], int end, List<String> result, ArrayList<String> tmp) {
        // 倒序打印路径
        if (end <= 0) {
            String path = tmp.get(tmp.size() - 1);
            for (int i = tmp.size() - 2; i >= 0; i--) {
                path += " " + tmp.get(i);
            }
            result.add(path);
            return;
        }
        for (String str : dp[end]) {
            tmp.add(str);
            dfs(dp, end - str.length(), result, tmp);
            // 删除以当前str的方案
            tmp.remove(tmp.size() - 1);
        }
    }

2. 测试代码

public static void main(String[] args) {
    String s = "catsanddog";
    Set<String> dict = new HashSet<>();
    dict.add("sand");
    dict.add("and");
    dict.add("cats");
    dict.add("cat");
    dict.add("dog");
    System.out.println(wordBreak(s,dict));
}

结果:

[cat sand dog, cats and dog]

进程已结束,退出代码 0
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用动态规划算法,采用 C 语言实现的代码: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_N 1000 #define MAX_WORD_LENGTH 50 #define INF 0x3f3f3f3f int dp[MAX_N + 1]; char s[MAX_N + 1]; char dictionary[MAX_N][MAX_WORD_LENGTH + 1]; int word_count; typedef struct TrieNode { int is_word; struct TrieNode* children[26]; } TrieNode; TrieNode* create_trie_node() { TrieNode* node = (TrieNode*)malloc(sizeof(TrieNode)); node->is_word = 0; memset(node->children, 0, sizeof(node->children)); return node; } void insert_word(TrieNode* root, char* word) { TrieNode* node = root; while (*word) { int idx = *word - 'a'; if (!node->children[idx]) { node->children[idx] = create_trie_node(); } node = node->children[idx]; ++word; } node->is_word = 1; } int search_word(TrieNode* root, char* word) { TrieNode* node = root; while (*word) { int idx = *word - 'a'; if (!node->children[idx]) { return 0; } node = node->children[idx]; ++word; } return node->is_word; } int main() { scanf("%s", s); scanf("%d", &word_count); TrieNode* root = create_trie_node(); for (int i = 0; i < word_count; ++i) { scanf("%s", dictionary[i]); insert_word(root, dictionary[i]); } int n = strlen(s); memset(dp, INF, sizeof(dp)); dp[0] = 0; for (int i = 1; i <= n; ++i) { for (int j = 0; j < i; ++j) { if (dp[j] != INF && search_word(root, s + j, i - j)) { dp[i] = dp[i] < dp[j] + i - j ? dp[i] : dp[j] + i - j; } } } printf("%d\n", dp[n]); return 0; } ``` 其,我们使用了一个 Trie 树来存储字典单词, Trie 树是一种高效的数据结构,可以用来快速查找字符串。在 insert_word 函数,我们依次遍历要插入的单词的每一个字符,将其插入到 Trie 树,如果该节点的 children 数组没有对应的字符,则新建一个 TrieNode 节点。在 search_word 函数,我们依次遍历要查询的字符串的每一个字符,判断该字符在当前节点的 children 数组是否存在,如果存在,则继续遍历,否则返回 0。 在主函数,我们首先读入字符串 s 和字典 dictionary,然后依次将字典单词插入到 Trie 树。接下来,我们使用动态规划算法,定义一个数组 dp,其 dp[i] 表示将字符串 s 的前 i 个字符分割成若干个互不重叠的子字符串,每个子字符串都在字典 dictionary 出现过,剩余的字符数最少是多少。初始时,我们将 dp 数组所有元素的值都赋为 INF,表示目前还没有找到符合要求的分割案。接下来,我们使用双重循环来遍历字符串 s 的所有子串,判断每个子串是否在字典 dictionary 出现过,并且以该子串为结尾的字符串能否被拆分。如果可以,更新 dp 数组的值。最终,当 dp[n] 的值不为 INF 时,表示字符串 s 可以被拆分成若干个互不重叠的子字符串,使得每个子字符串都在字典 dictionary 出现过,剩余的字符数最少是 dp[n]。 时间复杂度为 O(n^3),空间复杂度为 O(n^2),其 n 是字符串 s 的长度。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值