关于字符串的算法
来源:互联网 发布:淘宝店卖假货会怎么样 编辑:程序博客网 时间:2024/06/08 17:15
两个串是相同字母异序词
Two Strings Are Anagrams
lintcode: (158)Two Strings Are Anagrams
Clarification What is Anagram?
- Two strings are anagram if they can be the same after change the order of characters. ExampleGiven s = “abcd”, t = “dcab”, return true. Given s = “ab”, t = “ab”,
return true. Given s = “ab”, t = “ac”, return false
解题思路;
第一种解法:
这里可以采用哈希的方法,用map数组来标记是否字符出现过。并用一个二维数组记录下出现的次数。因为一个字符可能出现好多次,之后进行比较即可。map键值的求解方法为:target[i]-NULL。因为NULL的ASSIC值为0所以这里减去的话就会避免出现负数的可能性。
#include "string"#include "stdio.h"#include "iostream"using namespace std;bool anagram(string source, string target) { int i,count=0; int map[1001][2]; memset(map,0,sizeof(map)); if(source.length()!=target.length()) return false; for(i=0;i<target.length();i++) { map[target[i]-NULL][0]=1; map[target[i]-NULL][1]++; } for(i=0;i<source.length();i++) { if(map[source[i]-NULL][0]==1 && map[source[i]-NULL][1]>0) { count++; map[source[i]-NULL][1]--; } } if(count==source.length()) return true; return false;}int main(){ string source,target; getline(cin,source); getline(cin,target); cout<<anagram(source,target)<<endl;//相同的字母或者异序词 return 0;}
上面的算法很容易想到所以还可以进行优化:
我们可以设置一个数组letterCount,用来统计两个字符串中各个字符各自出现的次数,如果源字符串中出现一次,如果两个字符串是相同异序川,那么对应的目标字符串中也应该出现一次。由此我们可以知道
Count( source [ i ] )==Count( target [ i ] ).
#include "string"#include "stdio.h"#include "iostream"using namespace std;bool anagram(string source, string target) { int i,count=0; int letterCount[256]={0}; if(source.size()!=target.size()) return false; for(i=0;i<source.length();i++) { letterCount[source[i]]++; letterCount[target[i]]--; } for(i=0;i<source.length();i++) { if(letterCount[target[i]]!=0)//判断为0即可 return false; } return true;}int main(){ string source,target; getline(cin,source); getline(cin,target); cout<<anagram(source,target)<<endl;//相同的字母或者异序词 return 0;}
第二种解法:
这里可以直接对两个字符串进行排序,如果排序后二者完全相同,那么就是相同异序串。
#include "string"#include "stdio.h"#include "iostream"#include "algorithm"using namespace std;bool anagram(string source, string target) { if(source.size()!=target.size()) return false; sort(source.begin(),source.end()); sort(target.begin(),target.end()); if(source==target) return true; return false;}int main(){ string source,target; getline(cin,source); getline(cin,target); cout<<anagram(source,target)<<endl;//相同的字母或者异序词 return 0;}
0 0
- 关于字符串的算法
- 关于对称字符串的算法
- 关于字符串算法的总结
- 关于字符串的一些算法
- 关于字符串的几个算法
- 关于字符串匹配算法的survey
- 关于字符串匹配的算法(一)
- 关于字符串处理的一系列类似算法
- 若干关于 字符串 的小算法
- 关于字符串匹配的算法(%%%)
- 关于线性字符串匹配的算法-----KMP的算法
- 暴雪公司关于字符串匹配的hash算法
- 暴雪公司关于字符串匹配的hash算法
- 关于字符串匹配(单模式匹配)的各种算法
- 关于数组,字符串的几道面试题和算法题
- 暴雪公司关于字符串匹配的hash算法
- 暴雪公司关于字符串匹配的hash算法
- 关于字符串匹配Sunday算法的个人想法
- PhoneGap框架
- JavaWeb 文件 上传 下载
- 动画学习之Animate.css的使用与解析
- ubuntu14.04+ROS Indigo +Kinectv2安装指南
- 自定义Toast
- 关于字符串的算法
- C++ 继承
- NSURLSession
- [LightOJ 1284] Lights inside 3D Grid (概率+递推求通项公式)
- 手机刷机的起起落落---落落落
- 立体匹配算法介绍
- Activity的生命周期,你足够了解吗?
- 简单排序算法
- AC自动机 (hdu acm 2222)