Skip to content

Commit 25dfc53

Browse files
Longest Common Prefix: Accepted
1 parent 451bdff commit 25dfc53

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,7 @@ My accepted leetcode solutions to some of the common interview problems.
261261
- [Longest Word in Dictionary through Deleting](problems/src/string/LongestWordInDictonary.java) (Medium)
262262
- [Isomorphic Strings](problems/src/string/IsomorphicStrings.java) (Easy)
263263
- [String Compression](problems/src/string/StringCompression.java) (Easy)
264+
- [Longest Common Prefix](problems/src/string/LongestCommonPrefix.java) (Easy)
264265

265266
#### [Tree](problems/src/tree)
266267

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package string;
2+
3+
/**
4+
* Created by gouthamvidyapradhan on 12/04/2018.
5+
* Write a function to find the longest common prefix string amongst an array of strings.
6+
*
7+
* Solution: O(N x M) where N is the length of the given array and M is the max_length of a string.
8+
*/
9+
public class LongestCommonPrefix {
10+
/**
11+
* Main method
12+
* @param args
13+
*/
14+
public static void main(String[] args) throws Exception{
15+
String[] A = {"abc", "a", "adkd"};
16+
System.out.println(new LongestCommonPrefix().longestCommonPrefix(A));
17+
}
18+
19+
public String longestCommonPrefix(String[] strs) {
20+
if(strs.length == 0) return "";
21+
String result = strs[0];
22+
for(int i = 1; i < strs.length; i ++){
23+
String s = strs[i];
24+
for(int j = 0; j < result.length(); j++){
25+
if(j >= s.length() || result.charAt(j) != s.charAt(j)) {
26+
result = result.substring(0, j);
27+
break;
28+
}
29+
}
30+
}
31+
return result;
32+
}
33+
34+
}

0 commit comments

Comments
 (0)