Skip to content

Instantly share code, notes, and snippets.

@VegaFromLyra
Created June 2, 2015 17:44
Show Gist options
  • Save VegaFromLyra/22391e5e7b36e8a7bbac to your computer and use it in GitHub Desktop.
Save VegaFromLyra/22391e5e7b36e8a7bbac to your computer and use it in GitHub Desktop.
Valid phrase
using System;
using System.Collections.Generic;
using System.Text;
namespace validPhrases
{
/*
You're given a dictionary array of 50k valid words, called myDictionary. You are then
given a string of characters as input. Write a function that takes that string and
checks whether or not the characters you've received so far form a set of words.
A set of words contains no characters that are not part of larger words.
*/
public class Program
{
private static readonly Dictionary<string, int> _myDict = new Dictionary<string, int>
{
{ "the", 1},
{ "these", 1},
{ "sect", 1},
{ "section", 1},
{ "words", 1},
{ "sew", 1},
{ "or", 1},
{ "ion", 1},
{ "on", 1},
{ "word", 1},
};
public static void Main(string[] args)
{
test("thesewords");
test("thesewo");
test("thesection");
test("thethe");
test("thesion");
}
static void test(string s) {
Console.WriteLine("{0} is valid?: {1}", s, isValidPhrase(s));
}
static bool isValidPhrase(string input)
{
int actualLength = 0;
if (String.IsNullOrEmpty(input)) {
return false;
}
HashSet<string> flaggedWords = new HashSet<string>();
Dictionary<string, int> wordsSeenSoFar = new Dictionary<string, int>();
StringBuilder sb = new StringBuilder("");
bool done = false;
while (!done) {
for(int i = input.Length - 1; i >=0; i--) {
sb.Insert(0, input[i]);
if (_myDict.ContainsKey(sb.ToString()) && !flaggedWords.Contains(sb.ToString()) ) {
if (wordsSeenSoFar.ContainsKey(sb.ToString())) {
wordsSeenSoFar[sb.ToString()]++;
} else {
wordsSeenSoFar.Add(sb.ToString(), 1);
}
sb.Clear();
}
}
sb.Clear();
foreach(var word in wordsSeenSoFar.Keys) {
actualLength += (word.Length * wordsSeenSoFar[word]);
}
if ((actualLength == input.Length) || (wordsSeenSoFar.Count == 0)) {
done = true;
} else {
foreach(var word in wordsSeenSoFar.Keys) {
flaggedWords.Add(word);
}
wordsSeenSoFar.Clear();
actualLength = 0;
}
}
return actualLength == input.Length;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment