LeetCode Word Break 解题报告

44 篇文章 0 订阅
43 篇文章 0 订阅
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".

判断输入的字符串能否被拆分成字典中的两个单词。
例如:输入字符串"cars"  字典:"car", “ca”, "rs", 返回:true。

解题报告:

解法1:DFS,直接深搜,而且本题不要求字典中的单词唯一,所以DFS过程中不需要改变字典。但大数据TLE。

public class Solution {
    public boolean wordBreak(String s, Set<String> dict) {
        if(dict.size()==0) {
            return false;
        }
        Iterator<String> it = dict.iterator();
        while (it.hasNext()) {
            String str = it.next();
            if(s.equals(str)) {
                return true;
            }
            
            if(s.indexOf(str)==0) {
                if(wordBreak(s.substring(str.length()),dict)==true) {
                    return true;
                }
            }
       }
       return false;
    }
}

解法2:动态规划
我们定义状态数组:state[s.length()+1],state[i]代表:string[0,i-1] 可被字典中的单词分割。
状态转移方程:state[i] = {state[j]&&string[i,j]在字典中,0=<j<i}。
public boolean wordBreak(String s, Set<String> dict) {
        if(dict.isEmpty()) {
            return false;
        }
        if(s.length()==0) {
            return true;
        }
        
        int[] state = new int[s.length() + 1];
        state[0] = 1;
        for(int i=1;i<=s.length();i++) {
            for(int j=0;j<i;j++) {
                if(state[j]==1&&(dict.contains(s.substring(j,i))==true)) {
                    state[i] = 1;
                    break;
                }
            }
        }
        if(state[s.length()]==1) {
            return true;
        } else {
            return false;
        }
    }





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值