Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created June 23, 2016 01:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/f763ce5033ea4b152c7a56aaf98b7075 to your computer and use it in GitHub Desktop.
Save jianminchen/f763ce5033ea4b152c7a56aaf98b7075 to your computer and use it in GitHub Desktop.
Leetcode 139 - word break - set up a test case for the code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _139WordBreak
{
class Program
{
static void Main(string[] args)
{
// test case:
// s = "leetcode",
// dict = ["leet", "code"].
string s = "abcd";
string[] dict = new string[]{
"a", "b","c","d"
};
bool result = wordBreak(s, new HashSet<string>(dict.ToList()));
}
/*
* Leetcode 139 Word Break
*
*
* source code from:
* http://bangbingsyb.blogspot.ca/2014/11/leetcode-word-break-i-ii.html
*
* Try to analyze the problem.
*
* Use DFS to do search, but to avoid duplication in calculation,
* use an array dp to save S[0:i] - break or not
dp[i]:S[0:i-1] breakable or not。
for example, dp[1] - s[0] is breakable or not.
*
dp[0] = true
dp[i] = true if and only if:
1. there is one i-1 >= k >= 0,s[k:i-1] is in the dict。
2. s[0: k-1] is breakable,so dp[k] = true。
*
* C++ unorder_set vs C# HashSet
* http://stackoverflow.com/questions/3659044/comparison-of-c-stl-collections-and-c-sharp-collections
*/
public static bool wordBreak(
string s,
HashSet<string> dict) {
if (s == null || s.Length == 0)
return false;
int len = s.Length;
bool[] dp = new bool[len + 1];
dp[0] = true;
for(int i = 0; i < len; i++) {
// For each string with length i - (0 to len-1)
// Look into two substring:
// s.Substring(0, j) - first j chars
// s.Subsring(j, i-j+1) - rest of string
// For example, "abcd",
// also, first string iteration from:
// abcd, ""
// abc, "d"
// ab, "cd"
// a, "bcd"
// if first string can be constructed,
// and also rest of string is one word in dictionary,
// then set dp[i+1] true
for(int j = i; j>=0; j--) {
string firstRunner = s.Substring(0, j);
string secondRunner = s.Substring(j, i - j + 1);
// firstRunner should be true - in dictionary
// dp[j]
// j starts from i, i is from 0 to increment
//
if (dp[j] && dict.Contains(secondRunner))
{
dp[i+1] = true;
break;
}
}
}
return dp[len];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment