Witajcie , próbuję rozwiązać problem na spoju, mam kod, który działa jednak wywala mi time limit na spoju, jak można by go usprawnić żeby szybciej działał ?
Link do problemu na spoju:
https://www.spoj.com/problems/MORSE/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Morse
{
public class Program
{
public static List<string> words = new List<string>();
public static List<string> wordsMorse = new List<string>();
public static StringBuilder sb = new StringBuilder();
public static string morse;
public static string copyMorse = morse;
public static int result = 0;
public static Dictionary<string, string> alphabet = new Dictionary<string, string>()
{
{"A", ".-" },
{"B", "-..." },
{"C", "-.-." },
{"D","-.."},
{"E","."},
{"F","..-."},
{"G","--."},
{"H","...."},
{"I",".."},
{"J",".---"},
{"K","-.-"},
{"L",".-.."},
{"M","--"},
{"N","-."},
{"O","---"},
{"P",".--."},
{"Q","--.-"},
{"R",".-."},
{"S","..."},
{"T","-"},
{"U","..-"},
{"V","...-"},
{"W",".--"},
{"X","-..-"},
{"Y","-.--"},
};
public static void Main()
{
int tests = int.Parse(Console.ReadLine());
while (tests-- != 0)
{
morse = Console.ReadLine().Trim();
int wordsCount = int.Parse(Console.ReadLine());
while (wordsCount-- != 0)
{
words.Add(Console.ReadLine().Trim());
}
foreach (string w in words)
{
string text = w;
foreach (var entry in alphabet)
{
text = text.Replace(entry.Key, entry.Value);
}
if (morse.Contains(text))
wordsMorse.Add(text);
}
copyMorse = morse;
result = 0;
foreach (string wm in wordsMorse)
{
try
{
if (copyMorse.Substring(0, wm.Length) == (wm))
{
copyMorse = copyMorse.Remove(0, wm.Length);
if (copyMorse.Length != 0)
{
string temp = copyMorse;
findAll(temp);
}
else
result++;
}
else
copyMorse = morse;
}
catch (ArgumentOutOfRangeException)
{
continue;
}
}
sb.AppendLine(result.ToString());
result = 0;
copyMorse = "";
morse = "";
wordsMorse.Clear();
words.Clear();
}
Console.WriteLine(sb);
}
public static int findAll(string temp)
{
foreach (string wmx in wordsMorse)
{
try
{
if (copyMorse.Substring(0, wmx.Length) == (wmx))
{
copyMorse = copyMorse.Remove(0, wmx.Length);
if (copyMorse.Length != 0)
{
findAll(copyMorse);
}
else
{
result++;
copyMorse = temp;
}
}
else
{
copyMorse = temp;
}
}
catch (ArgumentOutOfRangeException)
{
continue;
}
}
return result;
}
}
}