Yu's Coding Garden : leetcode Quesion 6: Anagram
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
Analysis:
Anagrams is two strings are using the same characters.
One way to compare two strings is use sort(). e.g.
sort(str1.begin(), str1.end());
sort(str1.begin(), str1.end());
if (str1.compare(str2)==0) // when two strings are equal, the func returns 0
A more efficient way:
1. Scan the whole string vector, for each string, store to a hash map with the "ordered string" as the key. O(n).
2. Scan the whole hash map, output the values where for one key the number of value >=2. O(n)
Read full article from Yu's Coding Garden : leetcode Quesion 6: Anagram
No comments:
Post a Comment