【LeetCode Easy】014 Longest Common Prefix

Easy 014 Longest Common Prefix

Description:

find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". (注意要检查参数数组是否为空或==null)
==Example==
Input: ["flower","flow","flight"]
Output: "fl"

My Solution:

    • for循环找出数组中最短的那个单词,以这个单词为基准,两层for循环嵌套,外层for是遍历这个最短单词的每个字母,内层for是遍历全部单词,看其它单词这个位置的字母是否和最短单词同样,若都同样,继续向下遍历,如有不同的,break,返回当前的最长前缀
    • 时间复杂度O(n²)
    • 代码以下:
    • public String longestCommonPrefix(String[] strs) {
          if (strs == null || strs.length == 0)
              return "";
          String shortest = strs[0];
          String prefix = "";
          for(int i=1; i<strs.length; i++){
              if(strs[i].length() < shortest.length())
                  shortest = strs[i];
          }
      
          for(int i=0; i<shortest.length(); i++){
              int j = 0;
              for(; j<strs.length; j++){
                  if(strs[j].charAt(i) != shortest.charAt(i))
                      break;
                  if(j == strs.length-1)
                      prefix += String.valueOf(shortest.charAt(i));
              }
              if(j != strs.length)
                  break;
          }
          return prefix;
      }
    • 仍旧是先找出最短字符串,以该字符串为基准,看其它字符串是否startswith该字符串,若是有不符合的,就减去最短字符串的最后一个字母而后继续遍历其它字符串,直至全部字符串都startswith某个前缀或最短字符串被减为空串
    • 最坏状况下时间复杂度是O((shortest.length()-1) * n),这个最坏状况可能会好于第一种方法
    • 这个方法的时间已经很是短了,但有一点比较疑惑的是这个方法的空间复杂度比法一要高一点(挠头
    • (部分)代码以下:
    while (!shortest.equals("")){
               int j = 0;
               for (; j<strs.length; j++){
                   if (!strs[j].startsWith(shortest)){
                       shortest = shortest.substring(0,shortest.length()-1);
                       break;
                   }
               }
               if (j == strs.length)  //这里这个if若是忘写了就会死循环
                   return shortest;
           }
           return shortest;

Fast Solution

  1. 对My Solution的法二作一个改进,不须要找出最短字符串,直接用第一个字符串为基准就能够作了
相关文章
相关标签/搜索