Skip to content

Commit d1b467c

Browse files
solves ongest common prefix
1 parent 48606c8 commit d1b467c

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66
| 1 | [Two Sum](https://leetcode.com/problems/two-sum/) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/TwoSum.java) |
77
| 7 | [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/ReverseInteger.java) |
88
| 9 | [PalindromeNumber](https://leetcode.com/problems/palindrome-number/) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/PalindromeNumber.java) |
9-
| 2 | [Roman To Integer](https://leetcode.com/problems/roman-to-integer/) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/RomanToInteger.java) |
10-
| 2 | []() | Easy | |
9+
| 13 | [Roman To Integer](https://leetcode.com/problems/roman-to-integer/) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/RomanToInteger.java) |
10+
| 14 | [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) | Easy | |
1111
| 2 | []() | Easy | |
1212
| 2 | []() | Easy | |
1313
| 2 | []() | Easy | |

src/LongestCommonPrefix.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// https://leetcode.com/problems/longest-common-prefix/
2+
3+
public class LongestCommonPrefix {
4+
public static void main(String[] args) {
5+
6+
}
7+
8+
public String longestCommonPrefix(String[] array) {
9+
if (array.length == 0) {
10+
return "";
11+
}
12+
13+
String result = array[0];
14+
for (int index = 1 ; index < array.length ; index++) {
15+
result = longestCommonPrefix(result, array[index]);
16+
}
17+
return result;
18+
}
19+
20+
private String longestCommonPrefix(String first, String second) {
21+
for (int index = 0 ; index < first.length() && index < second.length() ; index++) {
22+
if (first.charAt(index) != second.charAt(index)) {
23+
return first.substring(0, index);
24+
}
25+
}
26+
return first.length() < second.length() ? first : second;
27+
}
28+
}

0 commit comments

Comments
 (0)