【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的法二作一個改進,不須要找出最短字符串,直接用第一個字符串爲基準就能夠作了
相關文章
相關標籤/搜索