[LeetCode]383. Ransom Note(赎金票据)

来源:互联网 发布:os系统教程加装windows 编辑:程序博客网 时间:2024/05/21 05:05

383. Ransom Note

Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
(给定一个任意的赎金票据字符串和另一个包含杂志上字母字符串,写一个函数,如果可以从杂志中构建赎金票据,则返回true; 否则会返回false。)

Each letter in the magazine string can only be used once in your ransom note.
(杂志字符串中的每个字母只能在您的赎金票据中使用一次。)

Note:
You may assume that both strings contain only lowercase letters.
(你可以假定两个字符串只包含小写字母。)

canConstruct("a", "b") -> falsecanConstruct("aa", "ab") -> falsecanConstruct("aa", "aab") -> true

题会做,但是题目刚开始没看懂,看了一个博客理解才题目的意思传送门:
题目叫做Ransom Note,勒索信,刚开始我还没理解这个题目的意思,尤其这个标题,和magazine有啥关系呢?后来仔细想想,才慢慢理解。勒索信,为了不暴露字迹,就从杂志上搜索各个需要的字母,组成单词来表达的意思。这样来说,题目也就清晰了,判断杂志上的字是否能够组成勒索信需要的那些字符。

代码1:

C++#include <iostream>#include <string>#include <vector>using namespace std;class Solution {public:    bool canConstruct(string ransomNote, string magazine) {        if (ransomNote.length() > magazine.length())            return false;        //考虑了大小写字母,如果只考虑小写字母把128改成26 下面验证的每个字符-97就好        vector <int> res(128, 0);//A-Z 65-90 a-z 97-122        for(char m : magazine)            res[m]++;        for(char r : ransomNote){            if(res[r] == 0)                return false;            res[r]--;        }        return true;    }};int main(){    Solution a;    string ransomNote,magazine;    cin >> ransomNote >> magazine;    cout << a.canConstruct(ransomNote, magazine) << endl;    return 0;}

代码2:·

 bool canConstruct(String ransomNote, String magazine) {        int[] arr = new int[26];        for (int i = 0; i < magazine.length(); i++) {            arr[magazine.charAt(i) - 'a']++;        }        for (int i = 0; i < ransomNote.length(); i++) {            if(--arr[ransomNote.charAt(i)-'a'] < 0) {                return false;            }        }        return true;    }
0 0