面试题 01.01. Is Unique LCCI
仅供自己学习
思路:
用hashmap存,将每个元素-‘0’然后得到的值作为索引,然后在加1,并判断如果这个索引的元素大于1,那么就有重复的元素,返回false;
1 class Solution { 2 public: 3 bool isUnique(string astr) { 4 unordered_map<int,int> mp; 5 for(int i=0;i<astr.length();++i){ 6 mp[astr[i]-'0']++; 7 if(mp[astr[i]-'0']>1) return false; 8 } 9 return true; 10 11 } 12 };
另一种方法是位运算,因为是字符,那么26位,将每一个元素-‘a’得到的数,作为这个二进制的位,那么就将他置1,如果下次再次到达这个位置,就返回false
代码:
1 class Solution { 2 public: 3 bool isUnique(string astr) { 4 int n=0; 5 for(auto& p:astr){ 6 int shift=p-'a'; 7 if((n&(1<<shift))!=0) return false; 8 else n|=1<<shift; 9 } 10 return true; 11 12 } 13 };