JAVA学习-练习试用Java实现“单词拆分 II”

问题:

给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。

说明:

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

输入:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]

输出:
[ "cats and dog", "cat sand dog"]

示例 2:

输入:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
输出:
[ "pine apple pen apple",
  "pineapple pen apple",
  "pine applepen apple"]
解释: 注意你可以重复使用字典中的单词。
示例 3:

输入:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
输出:
[]

解答思路:

一、题目分析:本题要求在给定的字符串中增加空格,构建所有可能的句子,使得句子中的单词都在给定的字典中。

二、主要思路:
1. 定义一个辅助函数,用于判断给定的字符串是否可以拆分成字典中的单词。
2. 使用回溯法,从字符串的开头开始,尝试将字符串拆分成单词。
3. 在回溯过程中,记录已经使用的单词,并在找到一种拆分方式后,将其加入结果列表中。

三、以下是修改后的 Java 代码:

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class WordBreakII {

    public List<String> wordBreak(String s, List<String> wordDict) {
        Set<String> wordSet = new HashSet<>(wordDict);
        List<String> result = new ArrayList<>();
        backtrack(s, wordSet, new ArrayList<>(), result);
        return result;
    }

    private void backtrack(String s, Set<String> wordSet, List<String> current, List<String> result) {
        if (s.isEmpty()) {
            result.add(String.join(" ", current));
            return;
        }

        for (String word : wordSet) {
            if (s.startsWith(word)) {
                current.add(word);
                backtrack(s.substring(word.length()), wordSet, current, result);
                current.remove(current.size() - 1);
            }
        }
    }

    public static void main(String[] args) {
        String s = "catsanddog";
        List<String> wordDict = List.of("cat", "cats", "and", "sand", "dog");

        WordBreakII solution = new WordBreakII();
        List<String> result = solution.wordBreak(s, wordDict);
        for (String sentence : result) {
            System.out.println(sentence);
        }
    }
}


(文章为作者在学习java过程中的一些个人体会总结和借鉴,如有不当、错误的地方,请各位大佬批评指正,定当努力改正,如有侵权请联系作者删帖。)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值