ID | Title | Difficulty | |
---|---|---|---|
Loading... |
14. Longest Common Prefix
Easy
LeetCode
String, Trie
Problem
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: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
Constraints:
- 1 <= strs.length <= 200
- 0 <= strs[i].length <= 200
- strs[i] consists of only lowercase English letters.
Code
class Solution {
public String longestCommonPrefix(String[] strs) {
String pre = strs[0];
for(int i = 1; i < strs.length; i++){
while(!strs[i].startsWith(pre)){
pre = pre.substring(0, pre.length() - 1);
}
}
return pre;
}
}
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
prefix = strs[0]
for s in strs:
if s.startswith(prefix):
continue
while len(prefix) != 0:
prefix = prefix[:-1]
if s.startswith(prefix):
break
return prefix
按 <- 键看上一题!
13. Roman to Integer
按 -> 键看下一题!
15. 3Sum