Skip to content

Commit

Permalink
find longest common prefix in java
Browse files Browse the repository at this point in the history
  • Loading branch information
kajurampatell authored Oct 31, 2022
1 parent 01965cb commit 88a8330
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions longestCommonPrefix.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
class Solution {
public String longestCommonPrefix(String[] strs) {
int minlength = 201;

for(int a=0;a <strs.length;a++){
String s = strs[a];
minlength = Math.min(minlength, s.length());
}
// System.out.println(minlength);

String st = "";
int count = 0;
while (count<= minlength){
for (int b=0; b<strs.length; b++){
if(count< minlength){
char tt =strs[0].charAt(count);
if(strs[b].charAt(count) != tt){
st = strs[0].substring(0, count);
System.out.println(st);
return st;
}

}
else if(count == minlength){
System.out.println(count);
System.out.println(minlength);
return st = strs[0].substring(0, count);
}


}
// System.out.println(count);
count++;
}


return st;
}
}

0 comments on commit 88a8330

Please sign in to comment.