I am doing the exercises in the Cracking The Coding Interview book and I am trying to determine if there is a duplicate character in a string. I am using the ArrayList data structure. My method is of return type Boolean, which returns true if there is a duplicate and returns false if there is no duplicate character. I added a third return statement so the program would compile but it always returns false.
import java.util.*;
public class QuestionOneCrackingCode {
public static void main(String[] args) {
String s = "abcdefga";
ArrayList<String> c = new ArrayList<String>();
c.add(s);
System.out.print(check(c));
}
public static boolean check(ArrayList<String> g) {
for (int i = 0; i < g.size(); i++) {
for (int j = i + 1; j < g.size(); j++) {
if (g.get(i) == g.get(j)) {
return true;
} else {
return false;
}
}
}
return false;
}
}
if (...) { return true; } else { return false; }can be simplified toreturn ...;.String, use acharvariable for the current char and do a search from the current position to the last or from the current position to the first. This saves time and it's easier to code..equals()it wouldn't work - the real problem is rather that he's expectingc.add(s)to split the String into characters when it's actually just going to result in a single-item list of the original String, which won't even get compared to anything. And if he was actually comparing chars,==would be correctStrings, notchars, check the parameter:ArrayList<String> gand its usage:g.get(i).