Skip to content

Commit f0df99c

Browse files
authored
Create LongestCommonPrefix.java
1 parent c8cd26c commit f0df99c

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

String/LongestCommonPrefix.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
//LeetCode 14. Longest Common Prefix
2+
//Question - https://leetcode.com/problems/longest-common-prefix/
3+
4+
class Solution {
5+
public String longestCommonPrefix(String[] strs) {
6+
int n = strs.length;
7+
if(n == 0) return "";
8+
9+
int minLen = Integer.MAX_VALUE;
10+
String s = null;
11+
int index = 0;
12+
boolean matched = false;
13+
14+
for(int i = 0 ; i < n ; i++){
15+
if(minLen > strs[i].length()){
16+
minLen = strs[i].length();
17+
s = strs[i];
18+
}
19+
}
20+
21+
for(int i = 0 ; i < minLen ; i++){
22+
for(String str : strs){
23+
if(str.charAt(i) != s.charAt(i)){
24+
return s.substring(0, index);
25+
}
26+
}
27+
index++;
28+
}
29+
30+
return s;
31+
}
32+
}

0 commit comments

Comments
 (0)