玩命加载中 . . .

242/383-有效的字母异位词


LeetCode 242. Valid Anagram

LeetCode-242

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: true

Example 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

LeetCode-383

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: false

Example 2:
Input: ransomNote = "aa", magazine = "ab"
Output: false

Example 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;
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录