is all different
given a string, determine if all of its characters are different
Solution:
It looks like pretty easy. However we can do better.
1. Ask the interviewer what's the charset for the string
2. if the charset is unicode, then just use hashset
3. if the charset is ASCII, we can use an array of length 256 to define the hashset (there are 256 characters in ASCII char set)
4. if the charset is only lowercase letters, we can use an Integer to define the hashset.
Code:
Unicode:
boolean isAllDifferent(String s){ Set<Character> hs = new HashSet<>(); for(int i = 0; i < s.length(); i++){ char c = s.charAt(i); if(!hs.contains(c)){ hs.add(c); }else{ return false; } } return true; }
ASCII:
boolean isAllDifferent(String s){ if(s.length>256) return false; boolean[] hasOccur = new boolean[256]; for(int i = 0; i < s.length(); i++){ char c = s.charAt(i); if(hasOccur[c]) return false; else hasOccur[c]=true; } return true; }
Lowercase letters:
boolean isAllDifferent(String s){ if(s.length()>26) return false; int hashset = 0; for(int i = 0; i < s.length(); i++){ int move = s.charAt(i)-'a'; if(hashset & (1<<move) == 0){ hashset|=(1<<move); }else return false; } return true; }

浙公网安备 33010602011771号