383. Ransom Note(map容器)
2018-02-26 17:50
295 查看
题目
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”) -> false
canConstruct(“aa”, “ab”) -> false
canConstruct(“aa”, “aab”) -> true
题意
判断字符串ransomNote中的元素是否是由magazine里的元素构成的。题解
C++代码
class Solution { public: bool canConstruct(string ransomNote, string magazine) { map<char, int>m; for(int i=0; i<magazine.length(); i++) { m[magazine[i]]++; } for(int i=0; i<ransomNote.length(); i++) { if(m[ransomNote[i]]==0) return false; m[ransomNote[i]]--; } return true; } };
python代码
class Solution(object): def canConstruct(self, ransomNote, magazine): """ :type ransomNote: str :type magazine: str :rtype: bool """ ransomNote = list(ransomNote) magazine = list(magazine) for i in range(0, len(ransomNote)): if ransomNote[i] in magazine: magazine.remove(ransomNote[i]) else: return False return True
相关文章推荐
- 静态数据成员(map容器)一定要记得初始化,否则出现链接错误
- map容器的使用
- 使用boost库serialize序列化map等STL容器的最常见错误——error C2039
- SGISTL源码探究-关联式容器:map
- Java容器-引用分类与部分Map用法
- LeetCode - 383. Ransom Note
- map容器
- STL中map容器的元素插入
- STL之红黑树容器:set,hash_set,multiset,hash_map,multimap
- 系统研究Java--容器(四)--Map和Set
- hdu1004Let the Balloon Rise(map容器经典例题)
- c++ 标准库的各种容器(vector,deque,map,set,unordered_map,unordered_set,list)的性能考虑
- Scala中常见的容器 Map
- NYOJ 685 查找字符串 字典树 map容器 吐血经验 cin cout 与printf scanf
- c++ 里面的map容器的迭代器 first second
- 【STL容器学习】-关联容器与map的用法
- java 容器类使用 Collection,Map,HashMap,hashTable,TreeMap,List,Vector,ArrayList的区别
- STL源码剖析——关联容器之map
- HDOJ 2094 产生冠军(map容器)