1.確定一個字符串每個字符都是獨一無二的

//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");
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章