hi used solve string char uniqueness using map in c++. found solution somewhere , working fine. can not understand how working. please 1 explain.
bool isunique(string s){ int check = 0; for(int i=0;i<s.length();++i){ if(s[i] != ' '){ int val = s[i]-'a'; if( (check & ( 1 << val)) > 0) return false; check = check | (1 << val); } } return true; } it returns true if string has no repeated character excluding spaces otherwise returns false.
it using int if bitmap. bitmap better data structure character uniqueness test map. int crude , questionable (in case) substitute bitmap.
assume int has 32 bits. bits allocated in code first 32 characters beginning lower case 'a'. upper case letters , special characters have no bit positions , treated unique code if not unique.
if care uniqueness lower case letters, , sure code used in architectures have @ least 32 bits in int, decent approach. otherwise, when want array of bits, use actual array of bits.
Comments
Post a Comment