383. Ransom Note
2016-10-08 21:21
337 查看
原题链接:https://leetcode.com/problems/ransom-note/
原题:
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.
题意:
给你两个字符串1和2,要去你判断能否用字符串2里面的字母组成字符串1,要求字符串2里面的字母一个只能用一次,能则return true 反之return false,给的字母都是小写字母。
思路:
用一个int数组保存26个小写字母在字符串2的出现次数,然后开始遍历字符串1,然后每次遇到一个字母,判断一次“库存”,不够,择return false,够则库存-1;遍历完成后,发现都够,则return true。
AC代码
原题:
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
题意:
给你两个字符串1和2,要去你判断能否用字符串2里面的字母组成字符串1,要求字符串2里面的字母一个只能用一次,能则return true 反之return false,给的字母都是小写字母。
思路:
用一个int数组保存26个小写字母在字符串2的出现次数,然后开始遍历字符串1,然后每次遇到一个字母,判断一次“库存”,不够,择return false,够则库存-1;遍历完成后,发现都够,则return true。
AC代码
class Solution { public: bool canConstruct(string ransomNote, string magazine) { int b[26]={0}; for(char s:magazine){ b[s-'a']++; } for(char s:ransomNote){ if(b[s-'a']==0) return false; b[s-'a']--; } return true; } };
相关文章推荐
- LeetCode 383. Ransom Note
- LeetCode383. Ransom Note优雅解法(线性时间复杂度)
- Leetcode 383. Ransom Note 构造字符串 解题报告
- 383. Ransom Note
- 383. Ransom Note
- 383. Ransom Note
- leetcode 383. Ransom Note
- 383. Ransom Note
- LeetCode 383. Ransom Note 解题报告
- LeetCode_383. Ransom Note
- 【Leetcode】383. Ransom Note
- leetcode 383. Ransom Note HashMap 统计字符 + HashMap
- leetcode(383. Ransom Note)
- 383. Ransom Note
- LeetCode笔记:383. Ransom Note
- 【leetcode】383. Ransom Note 恐吓信
- LeetCode之383. Ransom Note
- leetcode(85).383. Ransom Note
- 383. Ransom Note
- 383. Ransom Note