Can anybody tell me how to implement a program to check a string contains all unique chars ?
Similarly (and without arrays), use a HASH TABLE!
//psuedo code:
Run time is O(n) and memory space is better too since you don't need an array of 256 (asciis)
Set an array of booleans of size equal to the character set to false. (Constant time). Scan the string; for each character, inspect the array at the characater's slot; if true, string has duplicate characters. If false, set that slot to true and continue. If you get to the end without encountering a duplicate, there aren't any and the string only contains unique characters. Running time: O(n) when n is the lenght of the string, with a pretty small constant.
Make a set of the letters, and count the values.
set("adoihgoiaheg")
= set(['a', 'e', 'd', 'g', 'i', 'h', 'o'])
:
def hasUniqueLetters(str):
return (len(set(str)) == len(str))
>>> hasUniqueLetters("adoihgoiaheg")
False
If you are talking about an ASCII string:
Create an int array [0-255], one for each character index, initialised to zero.
Loop through each character in the string and increment the respective array position for that character
If the array position already contains a 1, then that character has already been encountered. Result => Not unique.
If you reach the end of the string with no occurrence of (3), Result => the string is unique.
#include <iostream>
#include <string>
using namespace std;
bool isUnique(string _str)
{
bool char_set[256];
int len = _str.length();
memset(char_set, '\0', 256);
for(int i = 0; i < len; ++i)
{
int val = _str[i]- '0';
if(char_set[val])
{
return false;
}
char_set[val] = true;
}
return true;
}
int main()
{
cout<<"Value: "<<isUnique("abcd")<<endl;
return 0;
}
I hope this can help you
#include <iostream>
using namespace std;
int main() {
string s;
cin>>s;
int a[256]={0};
int sum=0;
for (int i = 0; i < s.length();i++){
if(a[s[i]]==0)++sum;
a[s[i]]+=1;
}
cout<<(sum==s.length()?"yes":"no");
return 0;
}