Tea-time snacking!
PROBLEM: https://leetcode.com/problems/longest-common-prefix/
TIME-COMPLEXITY: O(n*m) where n is the number of strings in input and m is the length of longest common prefix.
Sample Java Solution for tea-time snacking:
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs.length == 1)
return strs[0];
int minLen = Integer.MAX_VALUE;
for (int i=0; i<strs.length; i++) {
minLen = Math.min(minLen, strs[i].length());
}
int lastPastIdx = minLen;
outer:
for (int i=0; i<minLen; i++) {
char ch = strs[0].charAt(i);
for (int str=0; str<strs.length; str++) {
if (strs[str].charAt(i) != ch) {
lastPastIdx = i;
break outer;
}
}
}
return strs[0].substring(0, lastPastIdx);
}
}
Enjoy and Happy Coding!!
Love! ❤️
#Lets #Code
Follow us on :
No comments:
Post a Comment