Two Strings Are Anagrams

题目:

Write a method anagram(s,t) to decide if two strings are anagrams or not.

Example
Given s = "abcd", t = "dcab", return true.
Given s = "ab", t = "ab", return true.
Given s = "ab", t = "ac", return false.

分析:

考虑ascii char就只做256个字符就可以了

解法:

class Solution {
public:
    /**
     * @param s: The first string
     * @param b: The second string
     * @return true or false
     */
    bool anagram(string s, string t) {
        // write your code here
        if (s.size() != t.size()) {
            return false;
        }
        vector<int> hash(256);
        for (int i = 0; i < s.size(); i++) {
            hash[s[i] - 'a' + 97] += 1;
            hash[t[i] - 'a' + 97] -= 1;
        }
        for (auto i : hash) {
            if (i != 0) {
                return false;
            }
        }
        return true;
    }
};

results matching ""

    No results matching ""