Leetcode: Longest Common Prefix

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

这道题做的不够顺利,许多次通过,但是居然是卡在一个小问题上了,判断strs是否为空,我想当然地就写成了if(strs == null) return null; 报错

java中null表示还没new出对象,就是还没开辟空间;“”表示new出了对象,但是这个对象装的是空字符串。这里显然是要应对strs[]为空数组的情况,数组为空,但是它已经在堆上开辟了空间。所以判空应该是 if (str.length == 0) return “”;

第二遍做法:时间复杂度应该是O(m*n),m表示字符串的最大长度,n表示字符串的个数,空间复杂度应该是O(m),即字符串的长度

 1 public class Solution {
 2     public String longestCommonPrefix(String[] strs) {
 3         if (strs==null || strs.length==0) return "";
 4         StringBuffer res = new StringBuffer();
 5         boolean isSame = true;
 6         for (int i=0; i<strs[0].length(); i++) {
 7             String test = strs[0].substring(0, i+1);
 8             for (int j=1; j<strs.length; j++) {
 9                 if (!strs[j].startsWith(test)) {
10                     isSame = false;
11                     break;
12                 }
13             }
14             if (isSame) {
15                 res.append(strs[0].charAt(i));
16             }
17             else break;
18         }
19         return res.toString();
20     }
21 }

不用startsWith函数:(最佳方法)

 1 public class Solution {
 2     public String longestCommonPrefix(String[] strs) {
 3         if (strs==null || strs.length==0) return "";
 4         StringBuffer res = new StringBuffer();
 5         boolean isSame = true;
 6         for (int i=0; i<strs[0].length(); i++) {
 7             char cur = strs[0].charAt(i);
 8             for (int j=1; j<strs.length; j++) {
 9                 if (i >= strs[j].length() || strs[j].charAt(i) != cur) {
10                     isSame = false;
11                     break;
12                 }
13             }
14             if (isSame) {
15                 res.append(cur);
16             }
17             else break;
18         }
19         return res.toString();
20     }
21 }

 Code Ganker的解法:以第一个字符串为标准,对于每个字符串从第一个字符开始,看看是不是和标准一致,如果不同,则跳出循环返回当前结果,否则继续下一个字符。时间复杂度应该是O(m*n),m表示字符串的最大长度,n表示字符串的个数,空间复杂度应该是O(m),即字符串的长度

 1 public String longestCommonPrefix(String[] strs) {
 2     StringBuilder res = new StringBuilder();
 3     if(strs == null || strs.length==0)
 4         return res.toString();
 5     boolean sameFlag = true;
 6     int idx = 0;
 7     while(sameFlag)
 8     {
 9         for(int i=0;i<strs.length;i++)
10         {
11             if(strs[i].length()<=idx || strs[i].charAt(idx)!=strs[0].charAt(idx))
12             {
13                 sameFlag = false;
14                 break;
15             }
16         }
17         if(sameFlag)
18             res.append(strs[0].charAt(idx));
19         idx++;
20     }
21     return res.toString();
22 }
原文地址:https://www.cnblogs.com/EdwardLiu/p/3715840.html