383.leetcode Ransom Note(easy)[字符统计]
来源:互联网 发布:网络教育学校名单 编辑:程序博客网 时间:2024/05/15 10:39
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
刚开始以为是子串匹配问题,后来发现是应该是字符统计问题,看ransomNote中需要的字符是否在magazine中出现足够的次数,
只要ransomNote出现的字符次数小于magazine中相同字符出现的次数即可。
class Solution {public: //子串匹配问题 /*bool canConstruct(string ransomNote, string magazine) { int n1 = ransomNote.size(); int n2 = magazine.size(); if(n1<=0||n2<=0) return false; char start = ransomNote[0]; vector<int> pos; for(int i=0;i<n2;i++) { if(magazine[i] == start) pos.push_back(i); } for(int i=0;i<pos.size();i++) { int j = pos[i]+1; int k = 1; while(k<n1&&j<n2&&ransomNote[k] == magazine[j]) { ++k; ++j; } //cout<<k<<""<<j<<endl; if(k==n1&&j<=n2) { return true; } } return false; }*/ //字符统计问题,看ransomNote中需要的字符是否否在magazine中出现足够的次数 bool canConstruct(string ransomNote, string magazine) { int n1 = ransomNote.size(); int n2 = magazine.size(); if(n1 == 0 && n2 == 0) return true; else if(n1 == 0) return true; else if(n2 == 0) return false; int status1[26];//ran统计 int status2[26];//magazine统计 memset(status1,0,sizeof(status1)); memset(status2,0,sizeof(status2)); for(int i=0;i<n1;i++) { status1[ransomNote[i]-'a']++; } for(int j=0;j<n2;j++) { status2[magazine[j]-'a']++; } for(int i=0;i<26;i++) { if(status1[i]>status2[i]) return false; } return true; }};
0 0
- 383.leetcode Ransom Note(easy)[字符统计]
- Leetcode 383. Ransom Note (Easy) (cpp)
- LeetCode解题报告 383. Ransom Note [easy]
- 383. Ransom Note [easy] (Python)
- 383. Ransom Note 难度:easy
- LeetCode-Easy部分中标签为String 383. Ransom Note
- 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
- Android 创建数据库的几种方法
- 小tips:nodeJs找不到模块 Cannot find module 'xxx'
- 四种内部类
- vsftpd软连接不能分享的解决方法
- CString转成String和函数f(x)=x+4/x的问题解答
- 383.leetcode Ransom Note(easy)[字符统计]
- shell (3) 拼写检查与词典操作
- C++一行一行的读文件
- Lonlife-ACM 1014 - Absolute Defeat [差分]
- linux下的pip安装
- Javascript模块化编程之【模块的写法】
- 基于cglib的动态代理
- oracle登入
- AS编译问题:Error:warning: Ignoring InnerClasses attribute for an anonymous inner class