LeetCode 383. Ransom Note
来源:互联网 发布:新手怎么做淘宝分销 编辑:程序博客网 时间:2024/05/29 18:53
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.
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
思路:
统计两个字符串中各个字符的数量,如果第一个字符串中每个字符数量都小于第二个字符串对应字符的数量,则返回true;否则,返回false。
方法1. 使用两个map<char,int>分别统计每个字符串中每个字符的数量,然后判断第一个字符串中字符数量是否是否小于第二个字符串中对应字符的字符数量。
方法2. 使用一个map,首先遍历第一个字符串,统计每个字符数量;然后遍历第二个字符串,遇见对应字符,字符数量减1;最后遍历map,如果所有字符数量均大于0,则返回true,否则返回false。
Code1:
class Solution {public: vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) { map<string,int> comResM; vector<string> comRes; vector<string> :: iterator it; int l1,l2; int sum=list1.size()+list2.size(); for(int i=0;i<list1.size();i++){ it = find(list2.begin(),list2.end(),list1[i]); if(it!=list2.end()){ l1=i; l2=distance(list2.begin(),it); comResM[list1[i]] = l1+l2; if((l1+l2)<sum) sum=l1+l2; } } for(auto & n:comResM){ if(n.second==sum) comRes.push_back(n.first); } return comRes; }};
Code2:
class Solution {public: vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) { unordered_map<string, int> hash1; for (int i = 0; i < list1.size(); i++) { hash1[list1[i]] = i; } unordered_map<int, vector<string> > ans; int min = 99999999; for (int j = 0; j < list2.size(); j++) { auto got = hash1.find(list2[j]); if (got != hash1.end()) { int common = got->second + j; if (common <= min) { min = common; ans[min].push_back(list2[j]); } } } return ans[min]; }};
阅读全文
0 0
- leetcode-383. Ransom Note
- [leetcode] 383. Ransom Note
- LeetCode 383. Ransom Note
- leetcode 383. Ransom Note
- leetcode 383. Ransom Note
- 383.[LeetCode]Ransom Note
- leetcode 383. Ransom Note
- leetcode 383. Ransom Note
- Leetcode 383. Ransom Note
- 【leetcode】383. Ransom Note
- Leetcode 383. Ransom Note
- LeetCode 383. Ransom Note
- [LeetCode]383. Ransom Note
- LeetCode 383. Ransom Note
- [LeetCode]--383. Ransom Note
- LeetCode 383. Ransom Note
- leetcode 383. Ransom Note
- 【LeetCode】 383. Ransom Note
- main(String [] args) eclipse入参设置
- PB9.0无法连接SQL Server数据库
- 汇编语言:在以GRADE为首地址的数组中存放着某班某门课30个学生的成绩。试编写一完整汇编语言程序实现:统计小于60分,60~89分和大于等于90分的学生人数,统计结果分别存放在LOWNUM、MIDD
- 安卓桌面图标对应的尺寸
- mybatis多数据源配置
- LeetCode 383. Ransom Note
- bzoj 4916 神犇和蒟蒻
- CMAKE的常见命令合集
- org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Can
- 217. Contains Duplicate
- 71. Simplify Path
- java中的排序!
- ubuntu16.04+cuda8.0+opencv3.1+GTX1080配置caffe
- CSS盒子模型