bool isUnique(string _str)
int len = _str.length();
memset(char_set, '\0', 256);
for(int i = 0; i < len; ++i)
int val = _str[i]- '0';
char_set[val] = true;
Hi....I came across this code to find if string has unique characters...i didnt understand why they subracted ascii value of character '0' in the statement int val = _str[i]- '0' and what is happening with the statements...if(char_set[val])
char_set[val] = true;
i take each character in the sting and traverse the whole string .and if count is 2 i use break and conclude that its not unique and not otherwise...can i use this method or this is not efficient????
This is just trying to create an index value for each printable character.
lets say _str has "hello world" in it.
int val =_str - '0' will give the ascii value of the first letter;
this will convert '0' to its ascii value 48 (is it 47 ?) and h to 104. So you will get 104 - 47 = 57;
similarly, for each character a unique value will be generated and then that index in char_set will be set to true;
in case that index is again generated (this will happen if that character will come again), then that index in char_set will already be true and it will be assumed that the character has already been seen and its not a unique string.
cant i work it out through alternative method like this...... i take each character in the sting and traverse the whole string .and if count is 2 i use break and conclude that its not unique and not otherwise...can i go this method or this is not efficient????
using this statement int val =_str - '0' what if one of the characters in the string has ascii value less than 48 and val turns into negative....then particular character will not get any place in char_set for its boolean......why cant we leave it like this...int value=str????
We are talking about printable characters or only numeric/alphabets. So, nothing like -ve will come.. because anything below ascii 48 will not be in the input. obviously you can change the code to include non-printable characters too.
You can do any method you like and which is easy to understand. the idea is to learn programming and not write optimal code at the moment.