现在的位置: 首页 > 综合 > 正文

1.确定一个字符串每个字符都是独一无二的

2017年11月15日 ⁄ 综合 ⁄ 共 575字 ⁄ 字号 评论关闭
//Implement an algorithm to determine if a string has all unique characters What if 
//you can not use additional data structures?
#include <iostream>
#include <string>
using namespace std;
//适合所有ascii字符

bool uniquechar1(string & s)
{
	bool a[256]={0};//ascii为256个
	int temp;
	for (auto i =0;i<s.size();i++)
	{
		temp=s[i];
		if(a[temp]) return false;
		a[temp] =true;
	}
	return true;
}
//只适合全为字母的字符串
bool uniquechar2(string & s)
{
	int temp;
	int val =0;
	for (auto i =0;i<s.size();i++)
	{
		temp=s[i]-'a';
		if((val&(1<<temp))>0) return false;
		val |=(1<<temp);
	}
	return true;
}


void main()
{
	string b;
	std::cin>>b;
	std::cout<<uniquechar1(b)<<" "<<uniquechar2(b);
	system("pause");
}

抱歉!评论已关闭.