Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures
选自careercup top 150 questions 1.1
#include<iostream>
#include<string>
using namespace std;
bool isUniqueChar(string str){
bool char_set[256]={0};
int val;
for(int i=0;i<str.length();i++){
val=str[i];
if(char_set[val])
return false;
char_set[val]=true;
}
return true;
}
int main(){
string s="gtyr";
bool b=isUniqueChar(s);
cout<<b<<endl;
b=isUniqueChar("abhgfb");
cout<<b<<endl;
system("pause");
return 0;
}假设字符是ASCII字符,每读入一个字符,把该字符ASCII值对应的char_set[]数组元素设置为true

本文介绍了一种算法,用于检查输入的字符串是否由全部不同的字符组成。通过使用一个布尔类型的数组来跟踪每个ASCII值是否已经出现过,该方法有效地解决了问题。示例代码展示了如何实现这一逻辑并进行测试。

被折叠的 条评论
为什么被折叠?



