Skip to content

Commit

Permalink
Time: 0 ms (100.00%), Space: 40.3 MB (88.85%) - LeetHub
Browse files Browse the repository at this point in the history
  • Loading branch information
hanull committed Dec 13, 2022
1 parent 88343e0 commit c6f46c1
Showing 1 changed file with 5 additions and 20 deletions.
25 changes: 5 additions & 20 deletions 0014-longest-common-prefix/0014-longest-common-prefix.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,12 @@ public String longestCommonPrefix(String[] strs) {
return strs[0];
}

Map<String, Integer> map = new HashMap<>();
for (int i=0; i<strs.length - 1; i++) {
String temp = "";
for (char c : strs[i].toCharArray()) {
temp += c;
if (map.containsKey(temp)) {
map.put(temp, map.get(temp) + 1);
} else {
map.put(temp, 1);
}
}
}
String answer = "";
String temp = "";
for (char c : strs[strs.length - 1].toCharArray()) {
temp += c;
if (map.containsKey(temp) && map.get(temp) == strs.length - 1) {
answer = temp;
String prefix = strs[0];
for (int i=1; i<strs.length; i++) {
while (strs[i].indexOf(prefix) != 0) {
prefix = prefix.substring(0, prefix.length() - 1);
}
}

return answer;
return prefix;
}
}

0 comments on commit c6f46c1

Please sign in to comment.