判断一个字符串的所有字符是否都是唯一的(使用hash表方法)

来源:互联网 发布:炒外汇模拟软件 编辑:程序博客网 时间:2024/06/01 09:23

哈希表几乎是最为重要的数据结构,主要用于基于“键”的查找,存储的基本单元是键-值对。逻辑上,数组可以作为哈希表的一个特例。以下将举出哈希表的两个应用。


1.判断一个字符串所有的字符是否都是唯一的


思路:这道题的关键是“唯一”,题目中一旦出现“唯一”,就考虑使用哈希表或者bitset来判断元素出现与否的范畴。使用bitset,需要建立字符到整数下标的映射关系。下面简单介绍一下bitset。

bitset位是用来保存一组项或者条件的yes/no的信息(有事也叫标志)的简洁方法。bitset必须声明自己有多少位,类似于vector的用法。

参考答案:

#include "stdafx.h"
#include<iostream>
#include<bitset>


using namespace std;


bool isUnique(string input)
{
bitset<256> hashMap;
for(int i=0;i<input.length();i++)
{
if(hashMap[(int)input[i]])
{
return false;
}
hashMap[(int)input[i]]=1;
}
return true;
}




int _tmain(int argc, _TCHAR* argv[])
{
string str;
bool Unique;
while(cin>>str)
{
Unique=isUnique(str);
cout<<Unique;
}
system("pause");
return 0;
}


2.给定两个字符串,判断他们是否是彼此可置换的


思路:判断两个字符串是否是可置换,即判断两个字符串中每个字符出现的次数是否是一样的。如果两个字符串的长度不一致,肯定是不能置换的。如相同的话,有两种方法判断,1是使用map,2是按照ASCII码排列。


参考答案:

#include "stdafx.h"
#include<iostream>
#include<string>
#include<unordered_map>


using namespace std;


bool isPertutation(string stringA,string stringB)
{
if(stringA.length()!=stringB.length())
{
return false;
}


unordered_map<char,int> hashMapA;
unordered_map<char,int>hashMapB;
for(int i=0;i<stringA.length();i++)
{
hashMapA[stringA[i]]++;
hashMapB[stringB[i]]++;
}


if(hashMapA.size()!=hashMapB.size())
{
return false;
}


unordered_map<char,int>::iterator it;
for(it=hashMapA.begin();it!=hashMapA.end();it++)
{
if(it->second!=hashMapB[it->first])
{
return false;
}
}
return true;
}




int _tmain(int argc, _TCHAR* argv[])
{
string str1="zzxxccvvbb";
string str2="bbvvxxcczz";
bool permutation=isPertutation(str1,str2);
cout<<permutation;
system("pause");
return 0;
}


0 0
原创粉丝点击