LeetCode-242. Valid Anagram

Given two strings s and , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

Note:
You may assume the string contains only lowercase alphabets.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

题解:

hash表即可。

class Solution {
public:
  bool isAnagram(string s, string t) {
    int n = s.length(), m = t.length();
    bool ans = true;
    if (n != m) {
      return false;
    }
    else if (n == 0) {
      return true;
    }
    int hash[26], cnt[26];
    for (int i = 0; i < 26; i++) {
      hash[i] = 0;
      cnt[i] = 0;
    }
    for (int i = 0; i < n; i++) {
      hash[s[i] - 97]++;
      cnt[t[i] - 97]++;
    }
    for (int i = 0; i < 26; i++) {
      if (cnt[i] != hash[i]) {
        ans = false;
        break;
      }
    }
    return ans;
  }
};

猜你喜欢

转载自blog.csdn.net/reigns_/article/details/84643534