File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
Algorithms/Easy/14_LongestCommonPrefix Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public static boolean isCommonForLength (int size , String [] strs ) {
3+ String substr = "" ;
4+
5+ for (String s : strs ) {
6+ if (s .length () < size ) {
7+ return false ;
8+ }
9+
10+ if (substr .equals ("" )) {
11+ substr = s .substring (0 , size );
12+ } else {
13+ if (!substr .equals (s .substring (0 , size ))) {
14+ return false ;
15+ }
16+ }
17+ }
18+
19+ return true ;
20+ }
21+
22+ public String longestCommonPrefix (String [] strs ) {
23+ int lo = 0 , hi = 201 , mid = 0 ;
24+
25+ for (int iter = 0 ; iter <= 8 ; iter ++) {
26+ mid = (lo + hi ) / 2 ;
27+
28+ if (isCommonForLength (mid , strs )) {
29+ lo = mid ;
30+ } else {
31+ hi = mid ;
32+ }
33+ }
34+
35+ return mid > 0 ? strs [0 ].substring (0 , mid ): "" ;
36+ }
37+ }
You can’t perform that action at this time.
0 commit comments