LeetCode #139. Word Break C#

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode #139. Word Break C#相关的知识,希望对你有一定的参考价值。

 

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

For example, given s = "leetcode", dict = ["leet", "code"].

Return true because "leetcode" can be segmented as "leet code".

 

Solution:

Need to use DP because derictly loop through the string may not return the correct answer.

Test case: s="aaaaaaa", dict = ["aaa", "aaaa"]

Two solutions:

First Dynamic programming:

dp[0] = true;// always true, because empty string can always add space to it.

dp[1] = dp[0]&&dict.Contains(s.Substring(0, 1);

dp[2] =( dp[1]&&dict.Contains(s.Substring(1,1))) ||(dp[0]&& dict.Contains(s.Substring(0,2)));

so need to loop through dp[j]&&wordDict.Contains(s.Substring(j,i-j)) untill dp[i] is true where j from 0 to i;

 1 public class Solution {
 2     public bool WordBreak(string s, ISet<string> wordDict)
 3         {
 4             ISet<int> set = new HashSet<int>();
 5             if(string.IsNullOrEmpty(s))
 6             {
 7                 return true;
 8             }
 9             int l = s.Length;
10             bool[] dp = new bool[l+1];
11             dp[0] = true;
12             for(int i=1; i<l+1; i++)
13             {
14                 for(int j=0; j<i; j++)
15                 {
16                     dp[i]=dp[j]&&wordDict.Contains(s.Substring(j,i-j));
17                     if(dp[i])
18                     {
19                         break;
20                     }
21                 }
22             }
23             return dp[l];
24         }
25        
26 }


Second DFS:

 

Use recursion in Dfs to mark the indexes those already looped through and returned false;

 

 1 public class Solution {
 2     public bool WordBreak(string s, ISet<string> wordDict)
 3         {
 4             ISet<int> set = new HashSet<int>();
 5             return Dfs(s, 0, wordDict, set);
 6 
 7         }
 8         private bool Dfs(string s, int index, ISet<string> dict, ISet<int> set)
 9         {
10             // base case
11             if (index == s.Length) return true;
12             // check memory
13             if (set.Contains(index)) return false;
14             // recursion
15             for (int i = index + 1; i <= s.Length; i++)
16             {
17                 String t = s.Substring(index, i-index);
18                 if (dict.Contains(t))
19                     if (Dfs(s, i, dict, set))
20                         return true;
21                     else
22                         set.Add(i);
23             }
24             set.Add(index);
25             return false;
26         }
27 }

 

  


以上是关于LeetCode #139. Word Break C#的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 139 Word Break

LeetCode #139. Word Break C#

Leetcode 139. Word Break

LeetCode 139: Word Break

leetcode 139. Word Break

LeetCode-139-Word Break