File tree Expand file tree Collapse file tree 3 files changed +206
-0
lines changed Expand file tree Collapse file tree 3 files changed +206
-0
lines changed Original file line number Diff line number Diff line change
1
+ ### [ 14\. Longest Common Prefix] ( https://leetcode.com/problems/longest-common-prefix/ )
2
+
3
+ Difficulty: ** Easy**
4
+
5
+
6
+ Write a function to find the longest common prefix string amongst an array of strings.
7
+
8
+ If there is no common prefix, return an empty string ` "" ` .
9
+
10
+ ** Example 1:**
11
+
12
+ ```
13
+ Input: ["flower","flow","flight"]
14
+ Output: "fl"
15
+ ```
16
+
17
+ ** Example 2:**
18
+
19
+ ```
20
+ Input: ["dog","racecar","car"]
21
+ Output: ""
22
+ Explanation: There is no common prefix among the input strings.
23
+ ```
24
+
25
+ ** Note:**
26
+
27
+ All given inputs are in lowercase letters ` a-z ` .
28
+
29
+
30
+ #### Solution
31
+
32
+ Language: ** Java**
33
+
34
+ ``` java
35
+ class Solution {
36
+ public String longestCommonPrefix (String [] strs ) {
37
+ if (strs. length == 0 ) {
38
+ return " " ;
39
+ }
40
+
41
+ if (strs. length == 1 ) {
42
+ return strs[0 ];
43
+ }
44
+ int minLenth = strs[0 ]. length();
45
+
46
+ for (String str : strs) {
47
+ if (minLenth > str. length()) {
48
+ minLenth = str. length();
49
+ }
50
+ }
51
+
52
+ for (int longPrefixIndex = 0 ; longPrefixIndex < minLenth; longPrefixIndex++ ) {
53
+ for (int j = 0 ; j < strs. length - 1 ; j++ ) {
54
+ if (strs[j]. charAt(longPrefixIndex) != strs[j + 1 ]. charAt(longPrefixIndex)) {
55
+ return strs[0 ]. substring(0 , longPrefixIndex);
56
+ }
57
+ }
58
+ }
59
+ return " " ;
60
+ }
61
+ }
62
+ ```
You can’t perform that action at this time.
0 commit comments