LeetCode 242. Valid Anagram
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: trueExample 2:
Input: s = "rat", t = "car"
Output: false
method: 哈希表
- 题意:就是看出现的字符数是不是一样的
用大小为26的数组存储每个字母出现的次数
bool isAnagram(string s, string t) {
int num1[26] = {0};
int num2[26] = {0};
for (auto n : s) num1[n - 'a']++;
for (auto n : t) num2[n - 'a']++;
for (int i = 0; i < 26; ++i) {
if (num1[i] != num2[i]) return false;
}
return true;
}
LeetCode 383. Ransom Note
Given two stings ransomNote and magazine, return true if ransomNote can be constructed from magazine and false otherwise.
Each letter in magazine can only be used once in ransomNote.
Example 1:
Input: ransomNote = "a", magazine = "b"
Output: falseExample 2:
Input: ransomNote = "aa", magazine = "ab"
Output: falseExample 3:
Input: ransomNote = "aa", magazine = "aab"
Output: true
method
- 题意:看
magazine的字符是不是比ransomNote的字符多
同样用哈希表存字符出现次数,用一个就可以了
bool canConstruct(string ransomNote, string magazine) {
int hash[26] = {0};
for (auto n : magazine) hash[n - 'a']++;
for (auto n : ransomNote) hash[n - 'a']--;
for (auto n : hash) {
if (n < 0) return false;
}
return true;
}