Longest Common Prefix Total Accepted: 24665 Total Submissions: 92370

My Submissions

Question

 Solution 

 

Write a function to find the longest common prefix string amongst an array of strings.

 

Show Tags

 

Have you met this question in a real interview? Yes No

 

Discuss

SOULTION1:

解法就是扫一次。不过各种边界条件很容易出错。

 1 public class Solution {
 2     public String longestCommonPrefix(String[] strs) {
 3         if (strs == null) {
 4             return null;
 5         }
 6         
 7         if (strs.length == 0 || strs[0].length() == 0) {
 8             return "";
 9         }
10         
11         int len = strs[0].length();
12         int i = 0;
13         for (; i < len; i++) {
14             char c = strs[0].charAt(i);
15             
16             int j = 1;
17             for (; j < strs.length; j++) {
18                 if (strs[j].length() <= i || c != strs[j].charAt(i)) {
19                     break;
20                 }
21             }
22             
23             // there is err.
24             if (j < strs.length) {
25                 break;
26             }
27         }
28         
29         // The char i is invalid. 因为读到i时退出,所以不应包含i本身。
30         return strs[0].substring(0, i);
31     }
32 }
View Code

相关文章:

  • 2022-03-07
  • 2021-09-18
  • 2021-12-24
  • 2021-12-12
  • 2022-01-18
  • 2021-08-02
猜你喜欢
  • 2021-12-31
  • 2021-06-01
  • 2022-12-23
  • 2021-12-28
  • 2022-01-09
  • 2021-09-25
  • 2022-02-24
相关资源
相似解决方案