您的位置:首页 > 其它

LeetCode 139 Word Break

2015-12-01 20:49 344 查看

题目描述

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

代码

[code]    public static boolean wordBreak(String s, Set<String> wordDict) {

        boolean[] P = new boolean[s.length() + 1];
        P[0] = true;

        for (int i = 0; i < s.length(); i++) {
            for (int j = 0; j <= i; j++) {
                if (P[j] && wordDict.contains(s.substring(j, i + 1))) {
                    P[i + 1] = true;
                }
            }
        }

        return P[s.length()];
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: