Skip to content

Commit 6a5058c

Browse files
committed
LongestCommonPrefix14
1 parent 40eaea7 commit 6a5058c

2 files changed

Lines changed: 42 additions & 1 deletion

File tree

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111

1212

13-
# Total: 50
13+
# Total: 51
1414

1515

1616
| Question | Solution | Difficulty |
@@ -20,6 +20,7 @@
2020
| [3. Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | [Solution](https://github.com/fluency03/leetcode-java/blob/master/src/LongestSubstringWithoutRepeatingCharacters3.java) | Medium |
2121
| [5. Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) | [Solution](https://github.com/fluency03/leetcode-java/blob/master/src/LongestPalindromicSubstring5.java) | Medium |
2222
| [8. String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | [Solution](https://github.com/fluency03/leetcode-java/blob/master/src/StringToInteger8.java) | Medium |
23+
| [14. Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) | [Solution](https://github.com/fluency03/leetcode-java/blob/master/src/LongestCommonPrefix14.java) | Easy |
2324
| [15. 3Sum](https://leetcode.com/problems/3sum/) | [Solution](https://github.com/fluency03/leetcode-java/blob/master/src/ThreeSum15.java) | Medium |
2425
| [16. 3Sum Closest](https://leetcode.com/problems/3sum-closest/) | [Solution](https://github.com/fluency03/leetcode-java/blob/master/src/ThreeSumClosest16.java) | Medium |
2526
| [20. Valid Parentheses](https://leetcode.com/problems/valid-parentheses/) | [Solution](https://github.com/fluency03/leetcode-java/blob/master/src/ValidParentheses20.java) | Easy |

src/LongestCommonPrefix14.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* Write a function to find the longest common prefix string amongst an array of strings.
3+
*/
4+
5+
6+
public class LongestCommonPrefix14 {
7+
public String longestCommonPrefix(String[] strs) {
8+
String lcp = "";
9+
int S = strs.length;
10+
if (S == 0) return lcp;
11+
12+
int L = strs[0].length();
13+
int idx = 0;
14+
for (int i = 1; i < S; i++) {
15+
if (strs[i].length() < L) {
16+
L = strs[i].length();
17+
idx = i;
18+
}
19+
}
20+
if (L == 0) return lcp;
21+
22+
int p = 1;
23+
String possible = strs[idx];
24+
while (p <= L) {
25+
String sub = possible.substring(0, p);
26+
boolean b = true;
27+
for (int k = 0; k < S; k++) {
28+
if (!strs[k].startsWith(sub)) {
29+
b = false;
30+
break;
31+
}
32+
}
33+
if (!b) break;
34+
lcp = sub;
35+
p++;
36+
}
37+
38+
return lcp;
39+
}
40+
}

0 commit comments

Comments
 (0)