Career Cup 刷题活动开始..............
第一题:Implement an algorithm to determine if a string has all unique characters What if you
can not use additional data structures?
思想:基本思想还是使用哈希,对数组中的每个元素对应到哈希表中并查看这个元素是否已经存在了。这个题计较基本的,使用简单的bitmap就可以完成。对于复杂的情况就需要设计更好一点的哈希表了,相信后面的题目会遇到这种情况的。
如果不使用额外空间的话,可以先使用快速排序来进行排序,然后再扫描一遍检查是否有相同的元素。
#include <iostream>
#include <cstring>
using namespace std;
// To check whether all the characters in the array are unique.
bool isUniqueArray(char* array, int size){
bool* bitmap = new bool[256+1];
memset(bitmap, 0, sizeof(bool)*(size+1));
for(int i=0; i<size; i++){
int position = array[i];
if( 0 == bitmap[position] ){
bitmap[position] = 1;
}else{
return false;
}
}
delete []bitmap;
return true;
}
int main(){
char list[] = "123456789abcdefg1";
bool ret = isUniqueArray(list, strlen(list));
if( ret ){
cout<<"Unique"<<endl;
}else{
cout<<"No "<<endl;
}
}