Tuesday, August 4, 2015

Valid Anagram #LeetCode

Question Reference:
https://leetcode.com/problems/valid-anagram/

Question Statement:

Given two strings s and t, write a function to determine if t is an anagram of s.
For example, s = "anagram", t = "nagaram", return true. s = "rat", t = "car", return false.
Note: You may assume the string contains only lowercase alphabets.

Solution:


Solution 1:
Get statistics map for each string and compare these two maps.


class Solution {
public:
    bool isAnagram(string s, string t) {
        std::unordered_map stats1 = getStats(s);
        std::unordered_map stats2 = getStats(t);
        if (stats1.size() != stats2.size()) {
            return false;
        }
        for (auto iter = stats1.begin(); iter != stats2.end(); iter++) {
            if (stats2.find(iter->first) == stats2.end() || stats2[iter->first] != iter->second) {
                return false;
            }
        }
        return true;
    }

    std::unordered_map getStats(string s) {
        std::unordered_map stats;
        for (char c : s) {
            if (stats.find(c) == stats.end()) {
                stats[c] = 1;
            } else {
                stats[c]++;
            }
        }
        return stats;
    }
};

Solution2:
Use an array to store statistics information.



class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.size() != t.size()) {
            return false;
        }
        vector stats(256, 0);
        for (char c : s) {
            stats[c]++;
        }
        for (char c : t) {
            stats[c]--;
        }
        for (int i = 0; i < 256; i++) {
            if (stats[i] != 0) {
                return false;
            }
        }
        return true;
    }
};

No comments:

Post a Comment