判断字符串全部为唯一字符
Implement an algorithm to determine if a string has all unique characters.What if you can not use additional data structures?
SOLUTION
For simplicity, assume char set is ASCII (if not, we need to increase the storage size. The rest of the logic would be the same).
1 class isUniqueChars2 { 2 public static boolean isUniqueChars(String str) { 3 boolean[] char_set = new boolean[256]; 4 for(int i=0; i<str.length(); i++) { 5 int val = str.charAt(i); 6 if(char_set[val]) return false; 7 char_set[val] = true; 8 } 9 return true; 10 } 11 12 public static void main(String[] args) { 13 System.out.println(isUniqueChars("aaabbb")); 14 System.out.println(isUniqueChars("abc")); 15 } 16 } 17
Time complexity is O(n), where n is the length of the string, and space complexity is O(n).
We can reduce our space usage a little bit by using a bit vector. We will assume, in the below code, that the string is only lower case ‘a’ through ‘z’. This will allow us to use just a single int .
1 class isUniqueChars { 2 public static boolean isUniqueCharsBit(String str) { 3 int checker = 0; 4 for(int i=0; i<str.length(); i++) { 5 int val = str.charAt(i) - 'a'; 6 if((checker & (1<<val)) > 0) return false;//注意加括号,>优先级高于& 7 checker |= (1<<val); 8 } 9 return true; 10 } 11 public static void main(String[] args) { 12 System.out.println(isUniqueCharsBit("aaabbb")); 13 System.out.println(isUniqueCharsBit("abcde")); 14 } 15 }
Alternatively, we could do the following:
1. Check every char of the string with every other char of the string for duplicate occurrences. This will take O(n^2) time and no space.
2. If we are allowed to destroy the input string, we could sort the string in O(n log n) time and then linearly check the string for neighboring characters that are identical. Careful, though - many sorting algorithms take up extra space.
浙公网安备 33010602011771号