File tree Expand file tree Collapse file tree 1 file changed +6
-13
lines changed
src/main/java/com/leetcode/strings Expand file tree Collapse file tree 1 file changed +6
-13
lines changed Original file line number Diff line number Diff line change @@ -14,34 +14,27 @@ public class LongestCommonPrefix {
1414 * r = no. of strings
1515 * c = max. no. of characters in a particular string
1616 * <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>.
1818 *
1919 * @param strs
2020 * @return
2121 */
2222 public static String longestCommonPrefix (String [] strs ) {
23- StringBuilder sb = new StringBuilder () ;
23+ if ( strs == null || strs . length == 0 ) return "" ;
2424
2525 int row ;
26- for (int col = 0 ; col < Integer . MAX_VALUE ; col ++) {
26+ for (int col = 0 ; col < strs [ 0 ]. length () ; col ++) {
2727 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
2929 if (col == strs [row ].length ()
3030 || col == strs [row + 1 ].length ()
3131 || strs [row ].charAt (col ) != strs [row + 1 ].charAt (col )) {
32- break ;
32+ return strs [ row ]. substring ( 0 , col ) ;
3333 }
3434 }
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- }
4235 }
4336
44- return sb . toString () ;
37+ return strs [ 0 ] ;
4538 }
4639
4740 public static void main (String [] args ) {
You can’t perform that action at this time.
0 commit comments