[编程之美-10]字符串的包含问题
来源:互联网 发布:淘宝hd ipad 编辑:程序博客网 时间:2024/06/14 10:05
[题目描述] 给定一长字符串 a 和一段字符串 b 。请问, 如何最快的判断出短字符串 b 中的所有字符是否都在长字符串 a 中。
[Sample Input]
ABCD BAD
ABCD BCE
ABCD AA
[Sample Output]
true
false
true
基本解法:我们遍历字符串b,依次判断b中的每个字符是不是的都在字符串a中。
代码如下:
#include<iostream>#include<string>using namespace std; bool stringContain(string &a, string &b);int main(){ string a, b; while(cin>>a>>b) { if(stringContain(a, b)) cout<< "true" << endl; else cout<< "false" << endl; } return 0; } bool stringContain(string &a, string &b){ for(int i = 0; i < b.length(); i ++) { if(a.find(b[i]) > b.length()) return false; } return true;}
时间复杂度:O(m*n), 空间复杂度:O(1)
高效算法:思考角度,我们都知道ASCII码一共有127个,而题目所说的字符串都是由ASCII码组合而成。首先遍历字符串a,将a中每个字符转化为int类型(作为数组角码)。并开辟数组大小为128的bool类型count数组。count[a[i]] = true.接着去遍历字符串b,依次判断每个字符是否count[b[i]] == true.
#include<iostream>#include<string>#include<string.h>using namespace std; bool stringContain(string &a, string &b);int main(){ string a, b; while(cin>>a>>b) { if(stringContain(a, b)) cout<< "true" << endl; else cout<< "false" << endl; } return 0; } bool stringContain(string &a, string &b){ bool count[128]; memset(count, false, sizeof(count)); for(int i = 0; i < a.length(); i ++) { count[a[i]] = true; } for(int i = 0; i < b.length(); i ++) { if(count[b[i]] == false) return false; } return true; }
时间复杂度:O(m+n), 空间复杂度:128B
0 0
- [编程之美-10]字符串的包含问题
- 编程之美之字符串移位包含的问题
- 编程之美---->字符串移位包含问题
- 《编程之美》3.1 字符串移位包含的问题
- [编程之美3.1]字符串移位包含的问题
- 字符串移位包含的问题(编程之美)
- 【编程之美】字符串移位包含的问题
- 编程之美--3.1字符串移位包含的问题
- 编程之美3.1 字符串移位包含的问题
- 3.1- 编程之美-字符串移位包含的问题
- 编程之美------3.1 字符串移位包含的问题
- [编程之美] PSet3.1 字符串移位包含的问题
- 字符串移位包含的问题(编程之美)
- 编程之美 3.1 字符串移位包含的问题
- 编程之美第三章-字符串移位包含的问题
- 编程之美 3.1字符串移位包含的问题
- 编程之美-字符串移位包含的问题
- 《编程之美》--字符串移位包含的问题
- 9. Palindrome Number
- 赛后总结(Codeforces Round #399 Div. 1)
- maven初学
- CSS3 修改和去除移动端点击事件出现的背景框 (tap-highlight-color)
- 关于form表单中使用ajax提交表单,ajax无法success的问题
- [编程之美-10]字符串的包含问题
- Apache的下载安装(主要说的 64位)及问题
- 信息安全工程师 学习笔记(五)
- 【PowerDesigner】:Generation aborted due to errors detected during the verification of the mod
- DPCM压缩实现
- 求js数组的最大值和最小值的四种方法
- 信息安全工程师 学习笔记(六)
- 2014年的笔记,整理文档搬过来
- 572. Subtree of Another Tree