Leetcode: word-break

题目一: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".


思路:

1.动态规划,利用dp保存状态,将字符串切割成小段

2.双层循环,判断当前是否能被有效分隔

代码:

import java.util.*;
public class Solution {
    public boolean wordBreak(String s, Set<String> dict) {
        boolean[] dp = new boolean[s.length()+1];
        dp[0] = true;
        for(int i=1; i<=s.length(); i++)
        {
            for(int j=0; j<i; j++)
            {
                if(dp[j] && dict.contains(s.substring(j,i)))
                {
                    dp[i] = true;
                }
            }
        }
        return dp[s.length()];
    }
}


题目二: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"].

思路:

1.将字符串递归分成左右两个部分s1,s2.若s1在字典里,则递归计算s2

2.当s2无法分割时,返回空ArrayList

3.当返回的ArrayList不为空是,将结果保存到ret

4.用map来记录递归状态,用于递归结束条件

代码:

import java.util.*;
public class Solution {
    Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
    public ArrayList<String> wordBreak(String s, Set<String> dict) {   
        if(map.containsKey(s))
            return map.get(s);
        ArrayList<String> ret = new ArrayList<String>();
        if(dict.contains(s))
            ret.add(s);
        for(int i=0; i<s.length(); i++)
        {
            String cur = s.substring(i);
            if(dict.contains(cur))
            {
                ArrayList<String> strs = wordBreak(s.substring(0,i), dict);
                if(strs.size() > 0)
                {
                    for(String str : strs)
                    {
                        ret.add(str + " " + cur);
                    }
                }
            }
        }
        map.put(s,ret);
        return ret; 
    }
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值