Word Break (Java)

来源:互联网 发布:中国人工智能技术 编辑:程序博客网 时间:2024/05/20 20:58

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