Meta interview question
Given a string, return the string with duplicate characters removed.
Interview Answers
Use a HashTable to count each occurence of characters. If it is already in the table, don't add it to the StringBuilder (we need an SB as String is immutable).
This is for case insensitive strings:
class Solution {
public static void main(String[] args) {
String word = "Fofobut1t1";
String noDup = stringReturner(word);
System.out.println(noDup);
}
public static String stringReturner(String strUpper){
if(strUpper.length() == 0){
return null;
} else if (strUpper.length() == 1){
return strUpper;
}
String str = strUpper.toLowerCase();
char[] a = str.toCharArray();
LinkedHashSet noDup = new LinkedHashSet ();
for(int i = 0; i < a.length; i++){
noDup.add(a[i]);
}
String s = "";
for(int i = 0; i < noDup.size(); i++){
s += noDup.toArray()[i];
}
return s;
}
}
1) Create ArrayList
2) Push first char of string into array
3) Iterate through the string and check if each char is already in the array
4) If it's not in array, push into array
5) O(n^2) time