Skip to content

Commit 1bf5b5b

Browse files
authored
Longest Common Prefix | String Matching using Sorting and Comparison (#3534)
2 parents 9f38699 + 706c103 commit 1bf5b5b

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

LongestCommonPrefix.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
public String longestCommonPrefix(String[] strs) {
3+
int n = strs.length;
4+
if(n == 0) return "";
5+
String prefix = strs[0];
6+
for(int i=1; i<n; i++){
7+
int j = 0;
8+
while(j<prefix.length() && j<strs[i].length() && prefix.charAt(j) == strs[i].charAt(j)){
9+
j++;
10+
}
11+
prefix = prefix.substring(0, j);
12+
if(prefix.length() == 0){
13+
return "";
14+
}
15+
}
16+
return prefix;
17+
}
18+
}

longestCommonPrefix.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
public String longestCommonPrefix(String[] strs) {
3+
int n = strs.length;
4+
if(n == 0) return "";
5+
String prefix = strs[0];
6+
for(int i=1; i<n; i++){
7+
int j = 0;
8+
while(j<prefix.length() && j<strs[i].length() && prefix.charAt(j) == strs[i].charAt(j)){
9+
j++;
10+
}
11+
prefix = prefix.substring(0, j);
12+
if(prefix.length() == 0){
13+
return "";
14+
}
15+
}
16+
return prefix;
17+
}
18+
}

0 commit comments

Comments
 (0)