This can almost certainly be optimized. Look at your algorithm:
- Take the next character from the first string
- Count all instances of that character in the both strings by iterating over them.
- Compare the count of the character in each string.
Now, let's look at how many times you iterate the strings: The first string is iterated N * N times, and the second string is iterated N * N times, where N is the count of the characters in the string. This makes 2N^2 iterations. It would probably be much faster (depending on the string length) to split these strings into character arrays, sort each of the arrays, and do an iteration like this:
list1 = Array.Sort(first.ToCharArray());
list2 = Array.Sort(second.ToCharArray());
for (var i = 0; i < list1.Count; i++)
if (list1[i] != list2[i])
I misunderstood what your program was meant to do the first time around.
First, you should understand that a permutation is:
Permutation: A way, especially one of several possible variations, in which a set or number of things can be ordered or arranged.
At first, I didn't understand that duplicate items within the string were not allowed.
Second, your program does not work correctly. Consider the following strings: "13234" and "43231". Your program will return
true for these values because the "3"s are in the same indexes in the string, and therefore the count for each item at the index matches. "123344" and "124433" also return
true because you only check that the items in the same index in each string have the same count.
To correctly handle this with your method, you would need to first compare the strings and return
true for duplicate values (e.g. "1233" is considered a "permutation" of "1233"). Then, you would need to check that the count of each item in the string is 1 and that each item is in the other string.
If I were to implement this program, I would do it as Paparazzi suggested, except I would check that each item is not already in the dictionary as I do the first iteration to prevent duplicates in the first string and ensure that the value is 1 every time I try to remove an item to prevent duplicates in the second string.
If you were sure that each string as no duplicates, you could use Dmitry's method, but you clearly do not expect each string to contain no duplicates because you attempted to rule out duplicates in your first solution.