LeetCode 0014. Longest Common Prefix Solution Java | Python | C/C++ | JavaScripts | Go | Rust | Explaination + CODE

CoderIndeed
0
0014. Longest Common Prefix

Description

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"

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

 

Constraints:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lowercase English letters if it is non-empty.

Solutions

Solution 1: Character Comparison

We use the first string strs[0] as a benchmark, and compare whether the i-th character of the subsequent strings is the same as the i-th character of strs[0]. If they are the same, we continue to compare the next character. Otherwise, we return the first i characters of strs[0].

If the traversal ends, it means that the first i characters of all strings are the same, and we return strs[0].

The time complexity is O(n × m), where n and m are the length of the string array and the minimum length of the strings, respectively. The space complexity is O(1).

PythonJavaC++GoTypeScriptRustJavaScriptC#PHPRubyC
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: for i in range(len(strs[0])): for s in strs[1:]: if len(s) <= i or s[i] != strs[0][i]: return s[:i] return strs[0](code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !