File tree 1 file changed +6
-13
lines changed
src/main/java/com/leetcode/strings
1 file changed +6
-13
lines changed Original file line number Diff line number Diff line change @@ -14,34 +14,27 @@ public class LongestCommonPrefix {
14
14
* r = no. of strings
15
15
* c = max. no. of characters in a particular string
16
16
* <p>
17
- * Runtime: <a href="https://leetcode.com/submissions/detail/223735469 /">1 ms</a>.
17
+ * Runtime: <a href="https://leetcode.com/submissions/detail/223737988 /">1 ms</a>.
18
18
*
19
19
* @param strs
20
20
* @return
21
21
*/
22
22
public static String longestCommonPrefix (String [] strs ) {
23
- StringBuilder sb = new StringBuilder () ;
23
+ if ( strs == null || strs . length == 0 ) return "" ;
24
24
25
25
int row ;
26
- for (int col = 0 ; col < Integer . MAX_VALUE ; col ++) {
26
+ for (int col = 0 ; col < strs [ 0 ]. length () ; col ++) {
27
27
for (row = 0 ; row < strs .length - 1 ; row ++) {
28
- // once we find a different character under one column, break the loop
28
+ // once we find a different character under one column, return the characters read so far
29
29
if (col == strs [row ].length ()
30
30
|| col == strs [row + 1 ].length ()
31
31
|| strs [row ].charAt (col ) != strs [row + 1 ].charAt (col )) {
32
- break ;
32
+ return strs [ row ]. substring ( 0 , col ) ;
33
33
}
34
34
}
35
-
36
- // check the row counter to figure whether all characters in a particular column are identical
37
- if (row == strs .length - 1 && strs [0 ].length () > 0 && col < strs [0 ].length ()) {
38
- sb .append (strs [0 ].charAt (col ));
39
- } else {
40
- break ;
41
- }
42
35
}
43
36
44
- return sb . toString () ;
37
+ return strs [ 0 ] ;
45
38
}
46
39
47
40
public static void main (String [] args ) {
You can’t perform that action at this time.
0 commit comments