leetcode 383. Ransom Note HashMap 统计字符 + HashMap
2017-10-08 13:16
513 查看
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
直接使用HashMap遍历即可。
代码如下:
下面是C++的做法,自己利用一个数组做统计即可
代码如下:
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
直接使用HashMap遍历即可。
代码如下:
import java.util.HashMap; import java.util.Map; class Solution { public boolean canConstruct(String ransomNote, String magazine) { if(ransomNote==null || magazine==null || ransomNote.length()>magazine.length()) return false; Map<Character, Integer> map=new HashMap<>(); for(int i=0;i<magazine.length();i++) map.put(magazine.charAt(i), map.getOrDefault(magazine.charAt(i), 0)+1); for(int i=0;i<ransomNote.length();i++) { if(map.containsKey(ransomNote.charAt(i))==false) return false; else { int size=map.get(ransomNote.charAt(i)); if(size==1) map.remove(ransomNote.charAt(i)); else map.put(ransomNote.charAt(i), size-1); } } return true; } }
下面是C++的做法,自己利用一个数组做统计即可
代码如下:
#include <iostream> #include <vector> #include <map> #include <unordered_map> #include <set> #include <unordered_set> #include <queue> #include <stack> #include <string> #include <climits> #include <algorithm> #include <sstream> #include <functional> #include <bitset> #include <numeric> #include <cmath> #include <regex> using namespace std; class Solution { public: bool canConstruct(string ransomNote, string magazine) { vector<int> count(26, 0); for (char c : magazine) count[c - 'a']++; for(char c : ransomNote) { count[c - 'a']--; if (count[c - 'a'] < 0) return false; } return true; } };
相关文章推荐
- 387.leetcode First Unique Character in a String(easy)[统计字符串字符次数]
- HashMap和HashSet使用--统计字符出现的次数
- 统计文件中字符个数BufferedReader BufferedWriter HashMap
- LeetCode 383. Ransom Note
- 小白笔记--------------leetcode(383. Ransom Note)
- Leetcode- 383. Ransom Note(string)
- Leetcode 383. Ransom Note (Easy) (cpp)
- LeetCode解题报告 383. Ransom Note [easy]
- leetcode(85).383. Ransom Note
- [leetcode]383. Ransom Note
- leetcode 383. Ransom Note 解题报告
- [LeetCode]383. Ransom Note(赎金票据)
- leetcode 383. Ransom Note
- Leetcode - String - 383. Ransom Note(水题)
- leetcode 383. Ransom Note
- LeetCode383. Ransom Note优雅解法(线性时间复杂度)
- 统计字符串中字符个数,通过HashMap和TreeMap分别按value和key排序
- leetcode 347. Top K Frequent Elements 将Hashmap统计次数的Entry,放到List<Entry>里面,对list排序后出现结果
- LeetCode-383. Ransom Note
- 383. Ransom Note [LeetCode]