LeetCode.Word Break

本文介绍了一种解决LeetCode单词拆分问题的有效方法。通过动态规划算法,判断给定字符串能否由字典中的单词完全匹配组成。文章详细解释了算法步骤,并提供了完整的Java实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

试题请参见: https://leetcode.com/problems/word-break/

题目概述

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

For example, given
s = "leetcode",
dict = ["leet", "code"].

Return true because "leetcode" can be segmented as "leet code".

解题思路

DP问题.

使用数组isMatched[i]表示字符串s[0, i - 1]是否可以被划分.

因此isMatched[s.length]表示字符串s是否可以被划分.

若isMatched[i] == true, 表示s[0, i - 1]可以被划分, 则需要同时满足如下条件之一:

  • isMatched[0] == true, 且s[0, i - 1]在dict中
  • isMatched[1] == true, 且s[1, i - 1]在dict中
  • isMatched[2] == true, 且s[2, i - 1]在dict中
  • `…
  • isMatched[i - 1] == true, 且s[i - 1, i - 1]在dict中

例如: s = "aaaaa", dict = { "aaaa", "aaa" }.

  1. isMatched[1] == false, 因为"a"不在dict中
  2. isMatched[2] == false, 因为"aa"不在dict中
  3. isMatched[3] == true, 因为"aaa"在dict中
  4. isMatched[4] == true, 因为"aaaa"在dict中
  5. 对于isMatched[5], 因为"aaaaa"不在dict中

    • 进而需要判断isMatched[1] = trues[1...4]在dict中, 显然前者不成立
    • 进而需要判断isMatched[2] = trues[2...4]在dict中, 显然前者不成立
    • 进而需要判断isMatched[3] = trues[3...4]在dict中, 显然后者不成立
    • 进而需要判断isMatched[4] = trues[4...4]在dict中, 显然后者不成立

因此isMatched[5] == false.

源代码

import java.util.HashSet;
import java.util.Set;

public class Solution {
    public boolean wordBreak(String s, Set<String> wordDict) {
        int length = s.length();
        boolean[] isMatched = new boolean[length + 1];
        isMatched[0] = true;

        for ( int i = 1; i  <= length; ++ i ) {
            for ( int j = 0; j < i; ++ j ) {
                if ( isMatched[j] && wordDict.contains(s.substring(j, i)) ) {
                    isMatched[i] = true;
                    break;
                }
            }
        }
        return isMatched[length];
    }

    public static void main(String[] args) {
        Solution s = new Solution();

        Set<String> set = new HashSet<String>();
        set.add("leet");
        set.add("code");
        System.out.println(s.wordBreak("leetcode", set));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值