I was asked the following question in an interview today which asks us to write a small program that checks whether two text sources might be in fact the same.
I was able to get a solution for checking whether two strings were the same length, otherwise, it's not a match. However, I tried to come up with a solution where I would first create a "filtered" array, that is, convert, for example A2Le
to A..Le
and then comparing it to 2pL1
which when filtered is ..pL.
. And I failed horribly there. Attached is my attempt:
int SLength = 0;
int TLength = 0;
String[] SParts = S.split("[^\\d]+");
String[] TParts = T.split("[^\\d]+");
for(int i = 0; i < SParts.length; i++) {
if(!SParts[i].equals("")){
SLength += Integer.parseInt(SParts[i]);
}
}
for(int i = 0; i < TParts.length; i++) {
if(!TParts[i].equals("")){
TLength += Integer.parseInt(TParts[i]);
}
}
for(int i = 0; i < S.length(); i++) {
if(!Character.isDigit(S.charAt(i))){
SLength += 1;
}
}
for(int i = 0; i < T.length(); i++) {
if(!Character.isDigit(T.charAt(i))){
TLength += 1;
}
}
if(TLength != SLength) {
return false;
}
// Convert String S from "A2Le" to "A..Le"
char[] sArray = S.toCharArray();
char[] sArrayFiltered = new char[SLength + 1];
int sIndex = 0;
for(int i = 0; i < sArray.length; i++) {
if(Character.isDigit(sArray[i])) {
sIndex += Character.getNumericValue(sArray[i]);
System.out.println("Digit Index: " + sIndex + ", Char: " + sArray[i] + ", Index: " + i);
} else {
sArrayFiltered[i] = sArray[sIndex];
sIndex++;
System.out.println("Char Index: " + sIndex + ", Char: " + sArray[i] + ", Index: " + i);
}
}
I kept getting IndexOutOfBoundExceptions
like this:
Char Index: 1, Char: A, Index: 0
Digit Index: 3, Char: 2, Index: 1
Char Index: 4, Char: L, Index: 2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at ReverseString.solution(ReverseString.java:192)
at ReverseString.main(ReverseString.java:210)
This example used the A2Le
sample string.
I tried to step my code through the debugger, but that did not seem to help me out.
EDIT: I know what the cause of the OutOfBoundException is - but not why it is being caused in the context of this problem. I'm not asking why I have an OutOfBound, but where.