Last active
August 29, 2015 14:21
-
-
Save joanmolinas/52e1b007c42e52683a63 to your computer and use it in GitHub Desktop.
Cracking the Coding Interview -> Arrays and String
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Implement an algorithm to determine if a string has a all unique characters. What if tou can not use additional data Structures? */ | |
/* Book Solution */ | |
public boolean isUniqueChars(String s) { | |
boolean[] char_set = new boolean[256]; | |
for (int i = 0; i < s.length(); i++) { | |
int val = s.charAt(i); | |
if(char_set[val]) return false; | |
char_set[val] = true; | |
} | |
return true; | |
} | |
/* My solution: it's the same but simplifying code */ | |
public boolean isUniqueCharsMine(String s) { | |
boolean[] char_set = new boolean[256]; | |
for (char c : s.toCharArray()) { | |
int val = c; | |
if(char_set[val]) return false; | |
char_set[val] = true; | |
} | |
return true; | |
} | |
/* Good Solution */ | |
public boolean goodSolution(String s) { | |
int checker = 0; | |
for (int i = 0; i < s.length(); i++) { | |
int val = s.charAt(i) - 'a'; | |
if((checker & (1<<val)) > 0) return false; | |
checker |= (1<<val); | |
} | |
return true; | |
} | |
/* EXAMPLE */ | |
String s = "capote"; | |
System.out.println(isUniqueChars(s)); -> //FALSE | |
s = "capota"; | |
System.out.println(isUniqueCharsMine(s)); //TRUE | |
System.out.println(goodSolution(s)); //TRUE |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Write code reverse an String */ | |
/* It's an accepted solution */ | |
public static String reverseBuilder(String s) { | |
return new StringBuilder(s).reverse().toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment