Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8a36c0e

Browse files
committed
Add Longest Common Prefix 💫
1 parent 43483ed commit 8a36c0e

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.anas.leetcode.easy;
2+
3+
public class LongestCommonPrefix {
4+
public String longestCommonPrefix(String[] strs) {
5+
String commonPrefix = strs[0];
6+
for (int i = 1; i < strs.length; i++) {
7+
String str = strs[i];
8+
if (commonPrefix.length() > str.length()) // if common prefix length less than str length
9+
commonPrefix = commonPrefix.substring(0, str.length()); // set common prefix to str length
10+
for (int j = commonPrefix.length() - 1; j >= 0; j--) {
11+
if (commonPrefix.charAt(j) != str.charAt(j)) {
12+
commonPrefix = commonPrefix.substring(0, j); // remove char
13+
j = commonPrefix.length(); // update j
14+
}
15+
16+
}
17+
}
18+
return commonPrefix;
19+
}
20+
21+
public static void main(String[] args) {
22+
LongestCommonPrefix lo = new LongestCommonPrefix();
23+
// Test 2
24+
System.out.println(lo.longestCommonPrefix(new String[]{"flower","flow","flight"}));
25+
// Test 1
26+
System.out.println(lo.longestCommonPrefix(new String[]{"dog","racecar","car"}));
27+
// Test 3
28+
System.out.println(lo.longestCommonPrefix(new String[]{"cir","car"}));
29+
}
30+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /