Tutorialspoint
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)
StringsGoogleKPMG
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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]

Steps to solve by this approach:

 Step 1: Create a HashSet from wordDict for O(1) lookups
 Step 2: Create a boolean array dp where dp[i] means the substring s[0...i-1] can be segmented
 Step 3: Set dp[0] = true as the base case (empty string)
 Step 4: For each position i in the string, check all previous positions j
 Step 5: If dp[j] is true and s[j...i-1] is in the dictionary, then dp[i] is true
 Step 6: If any such j exists, break the inner loop
 Step 7: Return dp[s.Length] as the final answer

Submitted Code :