How do you check if two strings are anagrams of each other?
String Coding
10/26/2020 10:06:20 PM
Dinusha Salith Perera
6 Answers
New AnswerA quick python example of the idea already expressed by NotAPythonNinja def check(word): return(sorted(word)) print(check('testing') == check('setting'))
Coder Kitten You could skip the frequency check and just do positional comparisons after sorting, then fail upon the first mismatch, otherwise return true after comparing all positions. Also, a short circuit validation could be to compare the lengths of both strings before sorting and return false if not equal. But, meh... may not be necessary.
NotAPythonNinja LOL... DOH... π€¦ββοΈ Yes... indeed... I completely agree. After sorting both values, a simple equality check is all that's needed. Coder Kitten I also agree that the algorithm you presented is consistent with the implementation. π Not that it's an excuse... I was a bit rushed in my original response as I saw the post on my way out the door, then tried to respond in the checkout line at the store. Somewhere in between, I got it in my head that we were working with a traditional array rather than a character array (a.k.a. string). That's what I get for multitasking. π€£ππ