
Problem
Solution
Submissions
Word Break
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a C# program to determine if a string can be segmented into a space-separated sequence of dictionary words. Implement the CanBreak(string s, IList<string> wordDict)
function, which returns true if the string can be segmented or false otherwise.
Example 1
- Input: s = "leetcode", wordDict = ["leet", "code"]
- Output: true
- Explanation:
- Step 1: Check if "leetcode" can be broken
- Step 2: Try "leet" which is in wordDict
- Step 3: Need to check "code" which is remaining
- Step 4: "code" is also in wordDict
- Step 5: All string has been segmented, return true
Example 2
- Input: s = "applepenapple", wordDict = ["apple", "pen"]
- Output: true
- Explanation:
- Step 1: Check if "applepenapple" can be broken
- Step 2: Try "apple" which is in wordDict
- Step 3: Need to check "penapple" which is remaining
- Step 4: Try "pen" which is in wordDict
- Step 5: Need to check "apple" which is remaining
- Step 6: "apple" is also in wordDict
- Step 7: All string has been segmented, return true
Constraints
- 1 <= s.length <= 300
- 1 <= wordDict.length <= 1000
- 1 <= wordDict[i].length <= 20
- s and wordDict[i] consist of only lowercase English letters
- Time Complexity: O(n²)
- Space Complexity: O(n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use dynamic programming to solve this problem efficiently
- Create a boolean array where dp[i] indicates whether the substring ending at index i can be segmented
- For each position, check all previous positions where a valid word could end
- If a valid segmentation is found up to a certain point, mark that point as true
- The final answer will be in dp[s.Length]