File tree Expand file tree Collapse file tree 2 files changed +35
-0
lines changed Expand file tree Collapse file tree 2 files changed +35
-0
lines changed Original file line number Diff line number Diff line change @@ -261,6 +261,7 @@ My accepted leetcode solutions to some of the common interview problems.
261
261
- [ Longest Word in Dictionary through Deleting] ( problems/src/string/LongestWordInDictonary.java ) (Medium)
262
262
- [ Isomorphic Strings] ( problems/src/string/IsomorphicStrings.java ) (Easy)
263
263
- [ String Compression] ( problems/src/string/StringCompression.java ) (Easy)
264
+ - [ Longest Common Prefix] ( problems/src/string/LongestCommonPrefix.java ) (Easy)
264
265
265
266
#### [ Tree] ( problems/src/tree )
266
267
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments