383. Ransom Note
来源:互联网 发布:手机直播美颜软件 编辑:程序博客网 时间:2024/05/21 22:28
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
#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; }};
0 0
- leetcode-383. Ransom Note
- [leetcode] 383. Ransom Note
- LeetCode 383. Ransom Note
- 383. Ransom Note*
- 383. Ransom Note
- leetcode 383. Ransom Note
- leetcode 383. Ransom Note
- 383. Ransom Note
- 383.[LeetCode]Ransom Note
- 383. Ransom Note
- 383. Ransom Note【E】
- leetcode 383. Ransom Note
- 383. Ransom Note
- 383. Ransom Note
- leetcode 383. Ransom Note
- Leetcode 383. Ransom Note
- 【leetcode】383. Ransom Note
- Leetcode 383. Ransom Note
- 完整的冒泡排序实现以及原理
- TRUNCATE TABLE 与 DELETE 区别
- List<Map<String,Object>几种遍历的方法
- kubernetes(2):Centos7 安装 kubernetes 1.5 版本
- CentOS 最小化安装系统安装图形界面
- 383. Ransom Note
- 第十三单元总结
- Android关于ListView滑动相关
- Linux下3个特殊的进程
- 关于本人将会搬家博客的声明
- FreeSpan 和 PrefixSpan 算法学习
- mongodb 使用入门介绍
- 二维线段树
- ReactNative系列之十对Http的Get和Post的简单封装