'Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings If there is no common prefix, return an empty string "". Example: Input: strs = ["flower","flow","flight"] Output: "fl" I'm new in coding and try to solve this problem (from leetcode). my way is search the shortest string between strings, here is my code, I can't figure out where did I do wrong, it seems the while loop doesn't work at all. I appreciate if someone could help me. here is my code:
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
string = ""
len_st = []
for st in strs:
len_st.append(len(st))
m = min(len_st)
prefix = strs[len_st.index(m)]
while prefix:
for st in strs:
if prefix in st:
continue
else:
prefix = prefix.replace(prefix[-1], "")
break
return prefix
else:
return ""
input : ["flower","flow","flight"] output: "flo" expected output: "fl"
Solution 1:[1]
Approach:
- First, we will find the shortest string and its length.
- Secondly, we will take the first string and match each character with the other strings.
- As soon as we encounter a character that does not fit, we will break out of the loop.
Code Solution :
public String longestCommonPrefix(String[] strs) {
// Longest common prefix string
StringBuilder longestCommonPrefix = new StringBuilder();
// Base condition
if (strs == null || strs.length == 0) {
return longestCommonPrefix.toString();
}
// Find the minimum length string from the array
int minimumLength = strs[0].length();
for (int i = 1; i < strs.length; i++) {
minimumLength = Math.min(minimumLength, strs[i].length());
}
// Loop for the minimum length
for (int i = 0; i < minimumLength; i++) {
// Get the current character from first string
char current = strs[0].charAt(i);
// Check if this character is found in all other strings or not
for (String str : strs) {
if (str.charAt(i) != current) {
return longestCommonPrefix.toString();
}
}
longestCommonPrefix.append(current);
}
return longestCommonPrefix.toString();
}
}
Time Complexity : O(m*n)
Space Complexity : O(1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
