These are questions from an interview:
- Reverse a string
- Find matching anagrams in a word list
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class ReverseString
{
public ReverseString()
{
string str = "Gilad";
string res = Reverse(str);
List<string> wordsList = new List<string>();
wordsList.Add("batel");
wordsList.Add("Gilad");
wordsList.Add("daliG");
wordsList.Add("enon");
wordsList.Add("none");
wordsList.Add("letab");
var pairs = PairAnagramWords(wordsList);
}
public string Reverse(string str)
{
StringBuilder s = new StringBuilder();
for (int i = str.Length - 1; i >= 0; i--)
{
s.Append(str[i]);
}
return s.ToString();
}
Dictionary<string, string> PairAnagramWords(List<string> wordsList)
{
wordsList.Sort();
Dictionary<string, string> res = new Dictionary<string, string>();
foreach (var item in wordsList)
{
if (res.ContainsValue(item))
{
continue;
}
foreach (var item2 in wordsList)
{
if (item == item2 || item.Length != item2.Length)
{
continue;
}
var reversed = Reverse(item2);
int i;
for (i = 0; i < item.Length; i++)
{
if (item[i] != reversed[i])
{
break;
}
}
if (i == item.Length)
{
res.Add(item, item2);
}
}
}
return res;
}
}
}
I don't like the fact that I'm doing it in \$ O(n^2) \$, although I am checking for no repetitions.
Please review my code's complexity and algorithm. I did the testing inside the constructor just for convenience, although I usually will use unit tests.