383. Ransom Note
2017-04-13 16:23
246 查看
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
#include <iostream> #include <string> #include <algorithm> using namespace std; class Solution { public: bool canConstruct(string ransomNote, string magazine) { if(ransomNote.length() > magazine.length()) return false; else { for(int i=0;i<ransomNote.length();i++) { bool flag = false; for(int j=0;j<magazine.length();j++) { if(ransomNote[i] == magazine[j]) { magazine[j] = '0'; flag = true; break; } } if(flag == false) return false; } return true; } } };
以下是来自评论区sharmilas的代码 使用了hashmap 截取下来以作参考
class Solution { public: bool canConstruct(string ransomNote, string magazine) {
int i=0,j=0; map <char ,int> h; while(i<m.length()) { h[m[i]]++; i++; } i=0; while(i<r.length()) { if(h.find(r[i])!=h.end()) { h[r[i]]=h[r[i]]-1; if(h[r[i]]==0) h.erase(h.find(r[i])); } else return false; i++; } return true; } };
相关文章推荐
- 383. Ransom Note
- LeetCode笔记:383. Ransom Note
- 【leetcode】383. Ransom Note 恐吓信
- LeetCode_383. Ransom Note
- 【Leetcode】383. Ransom Note
- 383. Ransom Note
- leetcode 383. Ransom Note
- LeetCode 383. Ransom Note 自己的解法
- 383. Ransom Note
- 383. Ransom Note
- LeetCode之383. Ransom Note
- leetcode(85).383. Ransom Note
- 383. Ransom Note
- 383. Ransom Note
- leecode 解题总结:383. Ransom Note
- LeetCode-Easy部分中标签为String 383. Ransom Note
- 383. Ransom Note(C语言)
- [leetcode]383. Ransom Note
- 383. Ransom Note
- leetcode 383. Ransom Note 勒索信