package com.app.main.LeetCode.dynamic;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* 139
*
* medium
*
* https://leetcode.com/problems/word-break/
*
* Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
*
* Note:
*
* The same word in the dictionary may be reused multiple times in the segmentation.
* You may assume the dictionary does not contain duplicate words.
* Example 1:
*
* Input: s = "leetcode", wordDict = ["leet", "code"]
* Output: true
* Explanation: Return true because "leetcode" can be segmented as "leet code".
* Example 2:
*
* Input: s = "applepenapple", wordDict = ["apple", "pen"]
* Output: true
* Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
* Note that you are allowed to reuse a dictionary word.
* Example 3:
*
* Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
* Output: false
*
*
* Created with IDEA
* author:Dingsheng Huang
* Date:2019/12/17
* Time:下午6:42
*/
public class WordBreak {
public boolean wordBreak(String s, List<String> wordDict) {
Set<String> set = new HashSet<>();
set.addAll(wordDict);
if (s.length() < 2) {
return set.contains(s);
}
boolean[] dp = new boolean[s.length()];
if (set.contains(s.substring(0, 1))) {
dp[0] = true;
} else {
dp[0] = false;
}
for(int i = 1; i < s.length(); i++) {
for (int j = i; j >= 0; j--) {
if (j == 0) {
dp[i] = set.contains(s.substring(j, i + 1));
} else {
dp[i] = dp[j - 1] && set.contains(s.substring(j, i + 1));
}
if (dp[i]) {
break;
}
}
}
return dp[s.length() - 1];
}
}
LeetCode--139--medium--WordBreak
猜你喜欢
转载自blog.csdn.net/huangdingsheng/article/details/103914835
今日推荐
周排行