File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ package easy ;
2
+
3
+ public class LongestCommonPrefix {
4
+
5
+ public static String longestCommonPrefix (String [] strs ) {
6
+ if (strs .length == 0 ) return "" ;
7
+
8
+ int i = 0 ;
9
+ String prefix = "" ;
10
+ String result = "" ;
11
+ boolean broken = false ;
12
+ while (true ){
13
+ i ++;
14
+ result = prefix ;
15
+ if (i > strs [0 ].length ()) break ;//this will break out the while loop
16
+ prefix = strs [0 ].substring (0 , i );
17
+ for (String word : strs ){
18
+ if (i > word .length () || !word .startsWith (prefix )) {
19
+ broken = true ;
20
+ break ;//this will only break out of the for loop
21
+ }
22
+ }
23
+ if (broken ) break ;//this will break out the while loop
24
+ }
25
+ return result ;
26
+ }
27
+
28
+ public static void main (String ...strings ){
29
+ // String[] strs = new String[]{"a"};
30
+ String [] strs = new String []{"a" , "b" };
31
+ System .out .println (longestCommonPrefix (strs ));
32
+ }
33
+ }
You can’t perform that action at this time.
0 commit comments