LeetCode word-break-ii

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”].

这道题的关键在于我们将字符串依次拆分成两部分来进行求解。
就像题目所给的 catsanddog, 列举前几部如何拆分

s1s2map
catsanddog
catsanddog
catwordBreak2(sanddog)sanddog
sanddog
sanddog
sanddog
sandwordBreak2(dog)dog
dog)
dog)
dogwordBreak2("")) )
sanddog
sanddog
sanddog“”
catswordBreak2(anddog)

为了防止重复计算,我们使用一个map来存放当前s所对应的可能解,并存放一个字符串为“”,其Arraylist存放的是一个“”,所以当上面直接遇到 wordBreak2(""),直接返回map.get("").

import java.util.*;
public class Solution {
    private Map<String, ArrayList<String>> map = new HashMap<>();
    
    public ArrayList<String> wordBreak(String s, Set<String> dict) {
    	// 当s切分到尾部无法切分的时候,递归结束
        map.put("", new ArrayList());
        map.get("").add("");
        return wordBreak2(s, dict);
    }
    
    public ArrayList<String> c(String s, Set<String> dict) {
        if (map.containsKey(s)) {
            return map.get(s);
        }
        ArrayList<String> ans = new ArrayList<>();
        for (int i = 1; i <= s.length(); i++) {
            String s1 = s.substring(0, i);
            String s2 = s.substring(i);
            if (dict.contains(s1)) {
            	// 进行下一个分割
                ArrayList<String> s2_rel = wordBreak(s2, dict);
                for (String str : s2_rel) {
                    if (str.equals("")) {
                        ans.add(s1);
                    } else {
                        ans.add(s1 + " " + str);
                    }
                }
            }
        }
        map.put(s, ans);
        return ans;
    }
}

参考:https://www.jiuzhang.com/solution/word-break-ii/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值