有效的字母异位词

242. 有效的字母异位词

给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。

注意:若 s 和 t 中每个字符出现的次数都相同,则称 s 和 t 互为字母异位词。

 

示例 1:

输入: s = "anagram", t = "nagaram"
输出: true

示例 2:

输入: s = "rat", t = "car"
输出: false

 

提示:

  • 1 <= s.length, t.length <= 5 * 104
  • s 和 t 仅包含小写字母
 1 #include <iostream>
 2 #include <vector>
 3 #include <unordered_map>
 4 
 5 using namespace std;
 6 
 7 class Solution {
 8 public:
 9     bool isAnagram(string s, string t) {
10         unordered_map<char, int> map1;
11         unordered_map<char, int> map2;
12         for (const auto &ch : s) {
13             map1[ch]++;
14         }
15         for (const auto &ch : t) {
16             map2[ch]++;
17         }
18         if (map1.size() != map2.size()) {
19             return false;
20         }
21         unordered_map<char, int>::iterator it1 = map1.begin();
22         for (; it1 != map1.end(); it1++) {
23             if (it1->second != map2[it1->first]) {
24                 return false;
25             }
26         }
27         return true;
28     }
29 };
30 
31 int main()
32 {
33     Solution *test = new Solution();
34     string s = "anagram";
35     string t = "nagaram";
36     std::cout << "s: " << s << ",t: " << t << endl;
37     std::cout << std::boolalpha;
38     std::cout << test->isAnagram(s, t) << endl; // true
39 
40     s = "rat";
41     t = "car";
42     std::cout << "s: " << s << ",t: " << t << endl;
43     std::cout << test->isAnagram(s, t) << endl; // false
44 
45     s = "";
46     t = "";
47     std::cout << "s: " << s << ",t: " << t << endl;
48     std::cout << test->isAnagram(s, t) << endl; // true
49 
50     s = "abcd";
51     t = "abc";
52     std::cout << "s: " << s << ",t: " << t << endl;
53     std::cout << test->isAnagram(s, t) << endl; // false
54 
55     delete test;
56     system("pause");
57     return 0;
58 }

运行结果:

 

 

posted @ 2022-03-05 13:33  跳动的休止符  阅读(39)  评论(0)    收藏  举报