Write a function to find the longest common prefix string amongst an array of strings.…
- User
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 1:
Input: strs = ["flower","flow","flight"] Output: "fl"
- Assistant
To find the longest common prefix among an array of strings, you can create a function that iteratively compares characters at the same position in each string. Here is an example function written in Python that does just that:
def longest_common_prefix(strs): if not strs: return "" # Find the shortest string in strs, which will be the maximum # possible length for the common prefix. min_length = min(len(s) for s in strs) # Initialize the longest common prefix to be an empty string. common_prefix = "" # Iterate over the characters up to the length of the shortest string. for i in range(min_length): # Take the character from the first string as a reference. char = strs[0][i] # Compare this character with the character at the same position # in each string. if all(s[i] == char for s in strs): common_prefix += char else: # As soon as a character doesn't match, we can stop and # return the current common prefix. break return common_prefix # Example usage: strs = ["flower","flow","flight"] print(longest_common_prefix(strs)) # Output: "fl" - User
char* longestCommonPrefix(char** strs, int strsSize) {
}
- Assistant