Skip to content

Instantly share code, notes, and snippets.

@joanmolinas
Last active August 29, 2015 14:21
Show Gist options
  • Save joanmolinas/52e1b007c42e52683a63 to your computer and use it in GitHub Desktop.
Save joanmolinas/52e1b007c42e52683a63 to your computer and use it in GitHub Desktop.
Cracking the Coding Interview -> Arrays and String
/* 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
/* 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