[LeetCode]Word BreakII

本文介绍了一种使用深度优先搜索(DFS)解决字符串拆分问题的方法,通过预先构建一个标记矩阵来快速判断子串是否存在于词典中,进而找出所有可能的拆分方式。

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

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.

Return all such possible sentences.

For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].

A solution is ["cats and dog", "cat sand dog"].

Analysis:

For the "Return all " problems, usually DFS or BFS will work well.

In this problem, a DFS with a simple cutting edge condition will pass all the test cases.

The idea is to use mp[][] array to record which substring is in dict. and a array to record the insert index

for those substrings, we use DFS. 

c++

class Solution {
public:
    void dfsWordBreak(string &s,
                  int st,
                  vector<int>&sp,
                  unordered_set<string> &dict,
                  vector<string> &result,
                  vector<vector<bool>> &mp){
    if(st>=s.size()){
        string str = s;
        for(int i=0;i<sp.size()-1;i++){
            str.insert(sp[i]+i," ");
        }
        result.push_back(str);
    }else{
        for(int j=0;j<mp[st].size();j++){
            if(mp[st][j]==true){
                sp.push_back(j+1);
                dfsWordBreak(s,j+1,sp,dict,result,mp);
                sp.pop_back();
            }
        }
    }
}
vector<string> wordBreak(string s, unordered_set<string> &dict) {
    vector<string> result;
    vector<vector<bool>> mp(s.size(),vector<bool>(s.size(),false));
    for(int i=0;i<s.size();i++){
        for(int j=i;j<s.size();j++){
            if(dict.find(s.substr(i,j-i+1))!=dict.end())
                mp[i][j] = true;
        }
    }
    bool flag = false;
    for(int i=0;i<s.size();i++){
        if(mp[i][s.size()-1])
            {flag = true;
            break;}
    }
    if(!flag) return result;
    vector<int>sp;
    dfsWordBreak(s,0,sp,dict,result,mp);
    return result;
}
};


Java

public class Solution {
    List<String> result;
	List<Integer> solu;
	boolean [][] mp;
	public List<String> wordBreak(String s, Set<String> dict) {
        result = new ArrayList<>();
        solu = new ArrayList<>();
        mp = new boolean[s.length()][s.length()];
        for(int i=0;i<s.length();i++){
        	for(int j=i;j<s.length();j++){
        		if(dict.contains(s.substring(i, j+1)))
        			mp[i][j] = true;
        	}
        }
        boolean flag = false;
        for(int i=0;i<s.length();i++){
        	if(mp[i][s.length()-1]){
        		flag = true;
        		break;
        	}
        }
        if(!flag) return result;
        dfs(s, 0, dict);
        return result;
    }
	public void dfs(String s, int st, Set<String> dict ){
		if(st>=s.length()){
			StringBuffer str = new StringBuffer(s);
			for(int i=0;i<solu.size()-1;i++){
				str.insert(solu.get(i)+i, " ");
			}
			result.add(str.toString());
		}else {
			for(int j=0;j<mp[st].length;j++){
				if(mp[st][j]==true){
					solu.add(j+1);
					dfs(s, j+1, dict);
					solu.remove(solu.size()-1);
				}
			}
		}
	}
}
### LeetCode Hot 100 Problems 列表 LeetCode 的热门题目列表通常由社区投票选出,涵盖了各种难度级别的经典编程挑战。这些题目对于准备技术面试非常有帮助。以下是部分 LeetCode 热门 100 题目列表: #### 数组与字符串 1. **两数之和 (Two Sum)** 2. **三数之和 (3Sum)** 3. **无重复字符的最长子串 (Longest Substring Without Repeating Characters)** 4. **寻找两个正序数组的中位数 (Median of Two Sorted Arrays)** #### 动态规划 5. **爬楼梯 (Climbing Stairs)** 6. **不同的二叉搜索树 (Unique Binary Search Trees)** 7. **最大子序列和 (Maximum Subarray)** #### 字符串处理 8. **有效的括号 (Valid Parentheses)** 9. **最小覆盖子串 (Minimum Window Substring)** 10. **字母异位词分组 (Group Anagrams)** #### 图论 11. **岛屿数量 (Number of Islands)** 12. **课程表 II (Course Schedule II)** #### 排序与查找 13. **最接近原点的 K 个点 (K Closest Points to Origin)** 14. **接雨水 (Trapping Rain Water)** 15. **最长连续序列 (Longest Consecutive Sequence)[^2]** #### 堆栈与队列 16. **每日温度 (Daily Temperatures)** 17. **滑动窗口最大值 (Sliding Window Maximum)** #### 树结构 18. **验证二叉搜索树 (Validate Binary Search Tree)** 19. **二叉树的最大路径和 (Binary Tree Maximum Path Sum)** 20. **从前序与中序遍历序列构造二叉树 (Construct Binary Tree from Preorder and Inorder Traversal)** #### 并查集 21. **冗余连接 II (Redundant Connection II)** #### 贪心算法 22. **跳跃游戏 (Jump Game)** 23. **分割等和子集 (Partition Equal Subset Sum)** #### 双指针技巧 24. **环形链表 II (Linked List Cycle II)[^1]** 25. **相交链表 (Intersection of Two Linked Lists)** #### 其他重要题目 26. **LRU缓存机制 (LRU Cache)** 27. **打家劫舍系列 (House Robber I & II)** 28. **编辑距离 (Edit Distance)** 29. **单词拆分 (Word Break)** 此列表并非官方发布版本而是基于社区反馈整理而成。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值