Word Break (Java)

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".

不怎么会写,参考了下别人的代码。

动态规划,不只是简单拼接,比如s="abcd", dic = "a","ab","bc",如果找到了与第一个字符匹配的“a”,很可能后面的就找不到了。

正确的做法是,用a[i]记录0~i-1的子串是否在dict中,如果在就将a[i] = true。搜索dict的时候 但凡子串里的前面的子串有false的就可以停止搜索了,比如dic = "ab","bc",在检查ab的时候,先检查a是否在dict中,发现不在,a[1] = false,再检查b时, 就直接跳过if语句了。

Source

public class Solution {
    public boolean wordBreak(String s, Set<String> dict) {
        if(s.length() == 0) return true;  //默认能找到
        boolean[] a = new boolean[s.length() + 1];  //默认为false
        a[0] = true; 
        
        for(int i = 0; i < s.length(); i++){
        	StringBuffer str = new StringBuffer(s.substring(0, i + 1));
        	for(int j = 0; j <= i; j++){
        		if(a[j] == true && dict.contains(str.toString())){  //注意 这里str是stringBuffer类型 如果不toString结果判断会出错
        			a[i + 1] = true;
        			break;
        		}
        		str.deleteCharAt(0);
        	}
        }
        return a[s.length()];
    }

}


Test

    public static void main(String[] args){
    	String s = "abcd";
    	Set<String> dict = new HashSet<String>();
    	dict.add("a");
    	dict.add("ab");
    	dict.add("cd");
    	
    	System.out.println(new Solution().wordBreak(s, dict));
    }


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值