1. 程式人生 > >【LeetCode】#139單詞拆分(Word Break)

【LeetCode】#139單詞拆分(Word Break)

【LeetCode】#139單詞拆分(Word Break)

題目描述

給定一個非空字串 s 和一個包含非空單詞列表的字典 wordDict,判定 s 是否可以被空格拆分為一個或多個在字典中出現的單詞。
說明:
1.拆分時可以重複使用字典中的單詞。
2.你可以假設字典中沒有重複的單詞。

示例

示例 1:

輸入: s = “leetcode”, wordDict = [“leet”, “code”]
輸出: true
解釋: 返回 true 因為 “leetcode” 可以被拆分成 “leet code”。

示例 2:

輸入: s = “applepenapple”, wordDict = [“apple”, “pen”]
輸出: true
解釋: 返回 true 因為 “applepenapple” 可以被拆分成 “apple pen apple”。
注意你可以重複使用字典中的單詞。

示例 3:

輸入: s = “catsandog”, wordDict = [“cats”, “dog”, “sand”, “and”, “cat”]
輸出: false

Description

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:
1.The same word in the dictionary may be reused multiple times in the segmentation.
2.You may assume the dictionary does not contain duplicate words.

Example

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

解法

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        int n = s.length();
        boolean[] memo = new boolean[n+1];
        memo[0] = true;
        for(int i=1; i<=n; i++){
            for(int j=0; j<i; j++){
                if(memo[j] && wordDict.contains(s.substring(j,i))){
                    memo[i] = true;
                    break;
                }
            }
        }
        return memo[n];
    }
}