LeetCode 383. Ransom Note
来源:互联网 发布:centos 7.0 安装cacti 编辑:程序博客网 时间:2024/06/14 00:20
题目 :
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的长度,如果ransomNote的长度大,直接返回false。如果ransomNote的长度大,直接返回false; 如果在magazine中找到第一个ransomNode[i],如果这个位置不是字符串中的最后(不过npos一般是-1),就将magazine中这个索引对应的字符删掉,继续循环,否则返回false。如果循环结束没有返回false,就可以构建,返回true。
代码:
class Solution {public: bool canConstruct(string ransomNote, string magazine) { int lenran=ransomNote.length();//分别计算ransomNote和magazine的长度 int lenmag=magazine.length(); if(lenran>lenmag){//如果ransomNote的长度大,直接返回false return false; } for(int i=0;i<lenran;++i){//遍历ransomNote int index=magazine.find_first_of(ransomNote[i]);//如果在magazine中找到第一个ransomNode[i] if(index!=string::npos){//如果这个位置不是字符串中的最后(不过npos一般是-1) magazine.erase(index,1);//就将magazine中这个索引对应的字符删掉,继续循环 continue; } else{//否则返回false return false; } } return true;//如果循环结束没有返回false,就可以构建,返回true }};
**输出结果:*42ms
- 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
- ACL框架简介
- Linux 三大文本处理命令之一AWK
- MyBatisSystemException测试类报错
- 三步测试只运行‘Test 3’
- 火狐插件(开发者)清空缓存
- LeetCode 383. Ransom Note
- Qt Stylesheet
- ROS action
- iOS开发 一句话隐藏导航栏下的黑线
- java集合迭代删除,一个很诡异的现象
- LeetCode 557. Reverse Words in a String III
- 离散点的曲率的计算
- 自己做个MP3_软件
- springmvc 参数绑定