題目
題目鏈接:383. 贖金信 - 力扣(LeetCode)
給你兩個字符串:ransomNote
和 magazine
,判斷 ransomNote
能不能由 magazine
里面的字符構成。
如果可以,返回 true
;否則返回 false
。
magazine
中的每個字符只能在 ransomNote
中使用一次。
ransomNote
和magazine
由小寫英文字母組成
輸入:ransomNote = "a", magazine = "b"
輸出:false
輸入:ransomNote = "aa", magazine = "aab"
輸出:true
class Solution {
public:bool canConstruct(string ransomNote, string magazine) {}
};
思路 & 代碼
數組做哈希表
該題 和 242.有效的字母異位詞 解題思路一樣。
#include <iostream>
#include <string>using namespace std;class Solution {
public:bool canConstruct(string ransomNote, string magazine) {int record[26] = {0};if(ransomNote.size() > magazine.size()) {return false;}for(int i = 0; i < magazine.size(); i++) {record[magazine[i] - 'a']++;}for(int i = 0; i < ransomNote.size(); i++) {record[ransomNote[i] - 'a']--;if(record[ransomNote[i] - 'a'] < 0) {return false;}}return true;}
};int main(){string s, t;cin >> s;cin >> t;cout << "s: " << s << endl;cout << "t: " << t << endl;Solution obj;bool res = obj.canConstruct(s, t);cout << boolalpha;cout << "res: " << res << endl;}