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?

题目大意:判断t是不是s的一个随机重排字符组成的字符串。

思路一:将s和t排序,排好序后,每个位置判断是否相同

思路二:只有小写字母,可以用大小为26的数组统计个数。(如果不止小写字母,可以用map)

 1 class Solution {
 2 public:
 3     bool isAnagram(string s, string t) {
 4         if (s.length() != t.length())
 5             return false;
 6         int cnt[26] = {0};
 7         for (int i = 0; i < s.length(); ++i) {
 8             cnt[s[i] - 'a']++;
 9             cnt[t[i] - 'a']--;
10         }
11         for (int i = 0; i < 26; ++i) {
12             if (cnt[i] != 0)
13                 return false;
14         }
15         return true;
16     }
17 };
原文地址:https://www.cnblogs.com/qinduanyinghua/p/11638249.html