Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1b3594f

Browse files
committed
Longest common prefix refactored and made simpler
1 parent df81753 commit 1b3594f

File tree

1 file changed

+6
-13
lines changed

1 file changed

+6
-13
lines changed

‎src/main/java/com/leetcode/strings/LongestCommonPrefix.java

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff 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-
StringBuildersb = newStringBuilder();
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+
returnstrs[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) {

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /