LeetCode383. Ransom Note

文章目录

    • 一、题目
    • 二、题解

一、题目

Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters 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

Constraints:

1 <= ransomNote.length, magazine.length <= 105
ransomNote and magazine consist of lowercase English letters.

二、题解

使用数组模拟哈希表解决

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        int n1 = ransomNote.length();
        int n2 = magazine.length();
        vector<int> chars(26,0);
        for(int i = 0;i < n2;i++){
            chars[magazine[i] - 'a']++; 
        }
        for(int i = 0;i < n1;i++){
            if(chars[ransomNote[i] - 'a'] == 0) return false;
            chars[ransomNote[i] - 'a']--;
        }
        return true;
    }
};

你可能感兴趣的:(算法,数据结构,leetcode,c++,面试)