Skip to content

Commit ac63d1e

Browse files
committed
14. Longest Common Prefix
```Solution.c char* longestCommonPrefix(char** strs, int strsSize) { if(strsSize==0) return ""; char* prefix=strs[0]; for(int i=1;i<strsSize;i++){ int j=0; while(prefix[j] && strs[i][j] && prefix[j]==strs[i][j]){ j++; } prefix[j]='\0'; } return prefix; } ``` ```Solution.cpp class Solution { public: string longestCommonPrefix(vector<string>& strs) { if (strs.empty()) return ""; string prefix = strs[0]; for (int i = 1; i < strs.size(); ++i) { while (strs[i].find(prefix) != 0) prefix = prefix.substr(0, prefix.length() - 1); if (prefix.empty()) return ""; } return prefix; } }; ``` ```Solution.cs public class Solution { public string LongestCommonPrefix(string[] strs) { if (strs.Length == 0) return ""; string prefix = strs[0]; for (int i = 1; i < strs.Length; i++) { while (!strs[i].StartsWith(prefix)) { prefix = prefix.Substring(0, prefix.Length - 1); if (prefix == "") return ""; } } return prefix; } } ``` ```Solution.dart class Solution { String longestCommonPrefix(List<String> strs) { if (strs.isEmpty) return ""; String prefix = strs[0]; for (var str in strs.skip(1)) { while (!str.startsWith(prefix)) { prefix = prefix.substring(0, prefix.length - 1); if (prefix.isEmpty) return ""; } } return prefix; } } ``` ```Solution.erl -spec longest_common_prefix(Strs :: [unicode:unicode_binary()]) -> unicode:unicode_binary(). longest_common_prefix([]) -> <<>>; longest_common_prefix([Prefix | Rest]) -> longest_common_prefix(Rest, Prefix). longest_common_prefix([], Prefix) -> Prefix; longest_common_prefix([H | T], Prefix) -> longest_common_prefix(T, common_prefix(Prefix, H)). common_prefix(A, B) -> common_prefix(A, B, <<>>). common_prefix(<<>>, _, Acc) -> Acc; common_prefix(_, <<>>, Acc) -> Acc; common_prefix(<<H1:8, T1/binary>>, <<H2:8, T2/binary>>, Acc) when H1 =:= H2 -> common_prefix(T1, T2, <<Acc/binary, H1>>); common_prefix(_, _, Acc) -> Acc. ``` ```Solution.ex defmodule Solution do @SPEC longest_common_prefix(strs :: [String.t]) :: String.t def longest_common_prefix([]), do: "" def longest_common_prefix([head | tail]) do Enum.reduce(tail, head, fn str, acc -> common_prefix(acc, str) end) end defp common_prefix(str1, str2) do str1 |> String.graphemes() |> Enum.zip(String.graphemes(str2)) |> Enum.take_while(fn {c1, c2} -> c1 == c2 end) |> Enum.map(fn {c, _} -> c end) |> Enum.join() end end ``` ```Solution.go func longestCommonPrefix(strs []string) string { if len(strs) == 0 { return "" } prefix := strs[0] for _, s := range strs[1:] { for !strings.HasPrefix(s, prefix) { prefix = prefix[:len(prefix)-1] if prefix == "" { return "" } } } return prefix } ``` ```Solution.java class Solution { public String longestCommonPrefix(String[] strs) { if (strs.length == 0) return ""; String prefix = strs[0]; for (int i = 1; i < strs.length; i++) { while (strs[i].indexOf(prefix) != 0) { prefix = prefix.substring(0, prefix.length() - 1); if (prefix.isEmpty()) return ""; } } return prefix; } } ``` ```Solution.js /** * @param {string[]} strs * @return {string} */ var longestCommonPrefix = function(strs) { if (!strs.length) return ""; let prefix = strs[0]; for (let i = 1; i < strs.length; i++) { while (!strs[i].startsWith(prefix)) { prefix = prefix.slice(0, -1); if (!prefix) return ""; } } return prefix; }; ``` ```Solution.kt class Solution { fun longestCommonPrefix(strs: Array<String>): String { if (strs.isEmpty()) return "" var prefix = strs[0] for (str in strs.drop(1)) { while (!str.startsWith(prefix)) { prefix = prefix.dropLast(1) if (prefix.isEmpty()) return "" } } return prefix } } ``` ```Solution.php class Solution { /** * @param String[] $strs * @return String */ function longestCommonPrefix($strs) { if (empty($strs)) return ""; $prefix = $strs[0]; for ($i = 1; $i < count($strs); $i++) { while (strpos($strs[$i], $prefix) !== 0) { $prefix = substr($prefix, 0, -1); if ($prefix === "") return ""; } } return $prefix; } } ``` ```Solution.py class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: if not strs: return "" prefix = strs[0] for s in strs[1:]: while not s.startswith(prefix): prefix = prefix[:-1] if not prefix: return "" return prefix ``` ```Solution.rb # @param {String[]} strs # @return {String} def longest_common_prefix(strs) return "" if strs.empty? prefix = strs[0] strs.each do |s| while !s.start_with?(prefix) prefix = prefix[0...-1] return "" if prefix.empty? end end prefix end ``` ```Solution.rkt (require racket/string) (define (longest-common-prefix strs) (if (null? strs) "" (let loop ((prefix (car strs)) (rest (cdr strs))) (cond [(null? rest) prefix] [else (define s (car rest)) (define (common p) (if (or (string=? p "") (string-prefix? s p)) p (common (substring p 0 (- (string-length p) 1))))) (loop (common prefix) (cdr rest))])))) ``` ```Solution.rs impl Solution { pub fn longest_common_prefix(strs: Vec<String>) -> String { if strs.is_empty() { return "".to_string(); } let mut prefix = strs[0].clone(); for s in strs.iter().skip(1) { while !s.starts_with(&prefix) { prefix.pop(); if prefix.is_empty() { return "".to_string(); } } } prefix } } ``` ```Solution.scala object Solution { def longestCommonPrefix(strs: Array[String]): String = { if (strs.isEmpty) return "" var prefix = strs(0) for(i <- 1 until strs.length) { while(!strs(i).startsWith(prefix) && prefix.nonEmpty) { prefix = prefix.substring(0,prefix.length-1) } } prefix } } ``` ```Solution.swift class Solution { func longestCommonPrefix(_ strs: [String]) -> String { if strs.isEmpty { return "" } var prefix = strs[0] for str in strs[1...] { while !str.hasPrefix(prefix) { prefix = String(prefix.dropLast()) if prefix.isEmpty { return "" } } } return prefix } } ``` ```Solution.ts function longestCommonPrefix(strs: string[]): string { if (strs.length === 0) return ""; let prefix = strs[0]; for (let i = 1; i < strs.length; i++) { while (!strs[i].startsWith(prefix)) { prefix = prefix.slice(0, -1); if (!prefix) return ""; } } return prefix; } ```
1 parent af22ecb commit ac63d1e

19 files changed

+270
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# [**14. Longest Common Prefix**](https://leetcode.com/problems/longest-common-prefix/description/)
2+
3+
Write a function to find the longest common prefix string amongst an array of strings.<br>
4+
If there is no common prefix, return an empty string `""`.
5+
6+
#### **Example 1:**
7+
```md
8+
Input: strs = ["flower","flow","flight"]
9+
Output: "fl"
10+
```
11+
12+
#### **Example 2:**
13+
```md
14+
Input: strs = ["dog","racecar","car"]
15+
Output: ""
16+
Explanation: There is no common prefix among the input strings.
17+
```
18+
19+
#### **Constraints:**
20+
> - `1 <= strs.length <= 200`
21+
> - `0 <= strs[i].length <= 200`
22+
> - `strs[i]` consists of only lowercase English letters if it is non-empty.
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
char* longestCommonPrefix(char** strs, int strsSize) {
2+
if(strsSize==0) return "";
3+
char* prefix=strs[0];
4+
for(int i=1;i<strsSize;i++){
5+
int j=0;
6+
while(prefix[j] && strs[i][j] && prefix[j]==strs[i][j]){
7+
j++;
8+
}
9+
prefix[j]='\0';
10+
}
11+
return prefix;
12+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Solution {
2+
public:
3+
string longestCommonPrefix(vector<string>& strs) {
4+
if (strs.empty()) return "";
5+
string prefix = strs[0];
6+
for (int i = 1; i < strs.size(); ++i) {
7+
while (strs[i].find(prefix) != 0)
8+
prefix = prefix.substr(0, prefix.length() - 1);
9+
if (prefix.empty()) return "";
10+
}
11+
return prefix;
12+
}
13+
};
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
public class Solution {
2+
public string LongestCommonPrefix(string[] strs) {
3+
if (strs.Length == 0) return "";
4+
string prefix = strs[0];
5+
for (int i = 1; i < strs.Length; i++) {
6+
while (!strs[i].StartsWith(prefix)) {
7+
prefix = prefix.Substring(0, prefix.Length - 1);
8+
if (prefix == "") return "";
9+
}
10+
}
11+
return prefix;
12+
}
13+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Solution {
2+
String longestCommonPrefix(List<String> strs) {
3+
if (strs.isEmpty) return "";
4+
String prefix = strs[0];
5+
for (var str in strs.skip(1)) {
6+
while (!str.startsWith(prefix)) {
7+
prefix = prefix.substring(0, prefix.length - 1);
8+
if (prefix.isEmpty) return "";
9+
}
10+
}
11+
return prefix;
12+
}
13+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
-spec longest_common_prefix(Strs :: [unicode:unicode_binary()]) -> unicode:unicode_binary().
2+
longest_common_prefix([]) -> <<>>;
3+
longest_common_prefix([Prefix | Rest]) ->
4+
longest_common_prefix(Rest, Prefix).
5+
longest_common_prefix([], Prefix) -> Prefix;
6+
longest_common_prefix([H | T], Prefix) ->
7+
longest_common_prefix(T, common_prefix(Prefix, H)).
8+
common_prefix(A, B) ->
9+
common_prefix(A, B, <<>>).
10+
common_prefix(<<>>, _, Acc) -> Acc;
11+
common_prefix(_, <<>>, Acc) -> Acc;
12+
common_prefix(<<H1:8, T1/binary>>, <<H2:8, T2/binary>>, Acc) when H1 =:= H2 ->
13+
common_prefix(T1, T2, <<Acc/binary, H1>>);
14+
common_prefix(_, _, Acc) -> Acc.
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
defmodule Solution do
2+
@spec longest_common_prefix(strs :: [String.t]) :: String.t
3+
def longest_common_prefix([]), do: ""
4+
def longest_common_prefix([head | tail]) do
5+
Enum.reduce(tail, head, fn str, acc ->
6+
common_prefix(acc, str)
7+
end)
8+
end
9+
defp common_prefix(str1, str2) do
10+
str1
11+
|> String.graphemes()
12+
|> Enum.zip(String.graphemes(str2))
13+
|> Enum.take_while(fn {c1, c2} -> c1 == c2 end)
14+
|> Enum.map(fn {c, _} -> c end)
15+
|> Enum.join()
16+
end
17+
end
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
func longestCommonPrefix(strs []string) string {
2+
if len(strs) == 0 {
3+
return ""
4+
}
5+
prefix := strs[0]
6+
for _, s := range strs[1:] {
7+
for !strings.HasPrefix(s, prefix) {
8+
prefix = prefix[:len(prefix)-1]
9+
if prefix == "" {
10+
return ""
11+
}
12+
}
13+
}
14+
return prefix
15+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Solution {
2+
public String longestCommonPrefix(String[] strs) {
3+
if (strs.length == 0) return "";
4+
String prefix = strs[0];
5+
for (int i = 1; i < strs.length; i++) {
6+
while (strs[i].indexOf(prefix) != 0) {
7+
prefix = prefix.substring(0, prefix.length() - 1);
8+
if (prefix.isEmpty()) return "";
9+
}
10+
}
11+
return prefix;
12+
}
13+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
/**
2+
* @param {string[]} strs
3+
* @return {string}
4+
*/
5+
var longestCommonPrefix = function(strs) {
6+
if (!strs.length) return "";
7+
let prefix = strs[0];
8+
for (let i = 1; i < strs.length; i++) {
9+
while (!strs[i].startsWith(prefix)) {
10+
prefix = prefix.slice(0, -1);
11+
if (!prefix) return "";
12+
}
13+
}
14+
return prefix;
15+
};

0 commit comments

Comments
 (0)