Anagrams

Given an array of strings, return all groups of strings that are anagrams.  

Note: All inputs will be in lower-case.

Solution:

First use an array to represent each string such that we can use linear time to compare whether two strings are the anagrams.

Then use map to quickly store and search the array.

Use another map to make sure all anagrams will be pushed back to the results.

The following code passes the LeetCode Online Large Judge.


class Solution {
public:
    vector<string> anagrams(vector<string> &strs) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<string> result;
        map<vector<int>, string> chkstr;
        map<vector<int>, int> ctr;
        for (int i = 0; i < strs.size(); i++) {
            vector<int> array(26);
            for (int j = 0; j < strs[i].size(); j++)
                array[strs[i][j] - 'a']++;
            if (chkstr.find(array) == chkstr.end()) {
                chkstr[array] = strs[i];
            }
            else {
                result.push_back(strs[i]);
                if (ctr[array] == 1) result.push_back(chkstr[array]);
            }
            ctr[array]++;
        }
        return result;
    }
};

Comments

Popular posts from this blog

Maximum Gap

[ITint5] Maximum Subarray for a Circular Array

[CC150] Chapter 4 Trees and Graphs