Skip to content

Commit

Permalink
14. Longest Common Prefix
Browse files Browse the repository at this point in the history
  • Loading branch information
SE-MahmoudAbdelaal committed May 20, 2024
1 parent 6dc6fc9 commit b1374bd
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions leetcode/easy/longestCommonPrefix.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import java.util.Arrays;

class Solution {
public String longestCommonPrefix(String[] v) {
StringBuilder ans = new StringBuilder();
Arrays.sort(v);
String first = v[0];
String last = v[v.length-1];
for (int i=0; i<Math.min(first.length(), last.length()); i++) {
if (first.charAt(i) != last.charAt(i)) {
return ans.toString();
}
ans.append(first.charAt(i));
}
return ans.toString();
}
}

0 comments on commit b1374bd

Please sign in to comment.