Confusded on what I'm doing wrong in LC problem
I'm doing the Longest Common Prefix LC problem, and got to 66 tests passing out of 126.
One of these tests is "["flower","flow","flight"]", and it's supposed to get "fl" back, but my code gives "flo" back. I've been trying to slowly chip away at these edge cases, but everything I try makes less tests pass in the end. I'm sure there are going to be further issues even after fixing this case, of course.
Please, even if my code "concept" is bad, I want to keep going with it. I'm not gonna restart from the beginning. I'm just a beginner programmer that only programs as a hobby.
class Solution {
public static String longestCommonPrefix(String[] strings) {
String prefix = "";
List<String> prefixStorage = new java.util.ArrayList<>(List.of());
for (int i = 0; i < strings.length; i++) {
int j = 0;
while (j < strings[i].length()) {
if (strings[i].isEmpty()) {
return "";
} else if (strings[i].length() == 1) {
prefix = strings[i];
} else if ((i < strings.length - 1) && (strings[i + 1].length() == 1)) {
prefix = strings[i + 1];
} else if ((i < strings.length - 1) && (j < strings[i].length()) && (j < strings[i + 1].length()) && strings[i].startsWith(strings[i + 1].substring(0, j)) && strings[i].substring(0, j).length() > prefix.length()) {
prefix = strings[i].substring(0, j);
}
j++;
}
prefixStorage.add(prefix);
}
List<String> sortedPrefixStorage = new java.util.ArrayList<>(prefixStorage.stream()
.sorted(Comparator.comparingInt(String::length))
.toList());
return sortedPrefixStorage.getFirst();
}
}