• Source
    1. class Practice1 {
    2. public static void main(String[] args) {
    3. // Inspired questions from Cracking the Coding Interview (http://www.amazon.com/dp/098478280X/)
    4. // CRACKING THE CODING INTERVIEW
    5. // 1.1 Implement an algorithm to determine if a string has all unique characters.
    6. // What if you can not use additional data structures?
    7. // http://asilearneveryday.blogspot.com/2015/01/implement-algorithm-to-determine-if.html
    8. System.out.println("Has word 'aacd' has unique characters? " + hasUniqueCharactersWithOneInteger("aacd"));
    9. System.out.println("Has word 'abcd' has unique characters? " + hasUniqueCharactersWithOneInteger("abcd"));
    10. System.out.println("Has word 'aacd' has unique characters? " + hasUniqueCharactersWithoutAdditionalDataStructures("aacd"));
    11. System.out.println("Has word 'abcd' has unique characters? " + hasUniqueCharactersWithoutAdditionalDataStructures("abcd"));
    12. System.out.println("Has word 'aacd' has unique characters? " + hasUniqueCharactersWithDataStructures("aacd"));
    13. System.out.println("Has word 'abcd' has unique characters? " + hasUniqueCharactersWithDataStructures("abcd"));
    14. }
    15. // LOGIC: Uses one integer and checks from 'a' and works for 32 characters.
    16. // RUNTIME: O(n), where n is the number of characters in the string
    17. public static boolean hasUniqueCharactersWithOneInteger(String str) {
    18. int characters=0;
    19. for(int i =0;i<str.length();i++) {
    20. int charIntValueFroma = str.charAt(i) - 'a';
    21. int bitRepresentation = 1<<charIntValueFroma;
    22. if((characters&bitRepresentation)>0) {
    23. return false;
    24. }
    25. characters |= bitRepresentation;
    26. }
    27. return true;
    28. }
    29. // LOGIC: Uses two loops to compare a character with every other character.
    30. // RUNTIME: O(n^2), where n is the number of characters in the string
    31. public static boolean hasUniqueCharactersWithoutAdditionalDataStructures(String str) {
    32. for(int i=0;i<str.length();i++) {
    33. for(int j=i+1;j<str.length();j++) {
    34. if(str.charAt(i)==str.charAt(j)) {
    35. return false;
    36. }
    37. }
    38. }
    39. return true;
    40. }
    41. // LOGIC: Using additional data structures
    42. // RUNTIME: O(n)
    43. public static boolean hasUniqueCharactersWithDataStructures(String str) {
    44. boolean[] characters=new boolean[256];
    45. for(int i =0;i<str.length();i++) {
    46. int charIndex = str.charAt(i)-'a';
    47. if(characters[charIndex]) {
    48. return false;
    49. }
    50. characters[charIndex]=true;
    51. }
    52. return true;
    53. }
    54. }