1.1 Implement an algorithm to determine if a string has all unique characters What if
you can not use additional data structures?
code:
//判断字符串中是否有重复字符,字符范围‘a-z’。 #include <iostream> #include <string> using namespace std; bool isUniqueChars(string str) { int checker = 0; for(int i = 0;i < str.length();++i) { int val = str.at(i) - 'a';//字符范围‘a-z’,故减去最小字符a即可。 cout << "checker: " << checker << "\t" << "val: " << val << endl; //checker & (1<< val))要么为零,要么为2的(1<<val)次方, //不同的字符产生不同的val,从而导致每次checker&(1<< val))=0 if((checker & (1<< val)) > 0) return false; //不同的字符产生不同的val,二进制形式的checker中每一个位可代表一个字符, //通过“或操作”填充checker中不同的二进制位 checker |= (1<< val); } return true; } int main() { if(isUniqueChars("ebceq")) cout << "无重复!"; else cout << "有重复!"; return 0; }