Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created June 23, 2016 17:53
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/29758bad5d56d54e87c2a6f52d057835 to your computer and use it in GitHub Desktop.
Save jianminchen/29758bad5d56d54e87c2a6f52d057835 to your computer and use it in GitHub Desktop.
Leetcode 139 - word break - warm up practice - work on DP algorithm in more detail - new variable names
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _139WordBreak6thPractice
{
class Program
{
static void Main(string[] args)
{
string s = "abcd";
string[] dict = new string[] {"a","bc","d" };
bool result = wordBreak(s, new HashSet<string>(dict.ToList()));
}
public static bool wordBreak(
string s,
ISet<string> wordDict
)
{
if (s == null || s.Length == 0)
return false;
int len = s.Length;
bool[] memorization = new bool[len + 1];
memorization[0] = true;
// work on Dynamic Programming - bottom up approach
// not top-down approach
// first loop is to handle bottom up, from first char in the
// string to the whole word as a string
for (int i = 0; i < len; i++)
{
// second loop, loop on the start position of new word
// start point starts from i decrementing 1 by 1 to 0.
// For exmaple, "abc", when working on i=2, 'c',
// new word {"c", "bc","abc"}
// use variable name startPos instead of pos
for (int startPos = i; startPos >= 0; startPos--)
{
// two words, first word is part of subproblem, processed string
int strToWorkOn = i+1; // string to work on: index 0 - i
string processedString = s.Substring(0, startPos);
int processed = processedString.Length;
string newWord = s.Substring(startPos, strToWorkOn - processed);
if(memorization[processed] && wordDict.Contains(newWord))
{
memorization[strToWorkOn] = true;
break;
}
}
}
return memorization[len];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment