Advertisement
Guest User

Longest word combination

a guest
Dec 8th, 2014
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.90 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6.  
  7. namespace SubstringSO
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             String input = "star, artifact, book, ctenophore, list, reply";
  14.             String pattern = "[a-zA-Z]+";
  15.  
  16.             var words = Regex.Matches(input, pattern).Cast<Match>().Select(m => m.Value).Where(r => r.Length >= 2);
  17.  
  18.             Dictionary<string, string> lookup = new Dictionary<string, string>();
  19.  
  20.             string maxString = "";
  21.  
  22.             foreach (var word in words)
  23.             {
  24.                 string initial = word.Substring(0, 2);
  25.                 string end = word.Substring(word.Length - 2, 2);
  26.                 if (!lookup.ContainsKey(initial))
  27.                 {
  28.                     if (!lookup.ContainsKey(end))
  29.                     {
  30.                         lookup.Add(end, word);
  31.                     }
  32.                     else if (lookup[end].Length < word.Length)
  33.                     {
  34.                         lookup[end] = word;
  35.                     }
  36.  
  37.                     if (word.Length > maxString.Length)
  38.                         maxString = word;
  39.                 }
  40.                 else
  41.                 {
  42.                     string newString = lookup[initial] + ", " + word;
  43.                     if (!lookup.ContainsKey(end))
  44.                     {
  45.                         lookup.Add(end, newString);
  46.                     }
  47.                     else if (lookup[end].Length < newString.Length)
  48.                     {
  49.                         lookup[end] = newString;
  50.                     }
  51.  
  52.                     if (newString.Length > maxString.Length)
  53.                         maxString = newString;
  54.                 }
  55.             }
  56.  
  57.  
  58.             Console.WriteLine(maxString);
  59.             Console.ReadKey();
  60.         }
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement