139.Word-Break
139. Word Break
题目地址
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代码
Approach 1: Brute Force
Complexity Analysis
Time complexity : O(n^n). Consider the worst case where s = "aaaaaaa" and every prefix of s is present in the dictionary of words, then the recursion tree can grow upto n^n.
Space complexity : O_(_n). The depth of the recursion tree can go upto n_n*.
Approach #2 Recursion with memoization
Complexity Analysis
Time complexity : O(n^2). Size of recursion tree can go up to n^2.
Space complexity : O(n). The depth of recursion tree can go up to n.
Approach #3 Using Breadth-First Search
Complexity Analysis
Time complexity : O(n^2). For every starting index, the search can continue till the end of the given string.
Space complexity : O_(_n). Queue of atmost n size is needed.
Approach #4 Using Dynamic Programming
Complexity Analysis
Time complexity : O(n^2). Two loops are their to fill dp array.
Space complexity : O_(_n). Length of p array is n + 1.
Last updated
Was this helpful?