[LeetCode] 1706. Where Will the Ball Fall
阿新 • • 發佈:2022-03-01
leetcode 242. 有效的字母異位詞
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> 45 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 (constauto &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 }
執行結果: