天天看點

Java算法-LeetCode14最長公共字首

題目位址:https://leetcode-cn.com/problems/longest-common-prefix/

編寫一個函數來查找字元串數組中的最長公共字首。

如果不存在公共字首,傳回空字元串 ""。

示例 1:

輸入: ["flower","flow","flight"]
輸出: "fl"
示例 2:

輸入: ["dog","racecar","car"]
輸出: ""
解釋: 輸入不存在公共字首。
說明:

所有輸入隻包含小寫字母 a-z 。

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/longest-common-prefix
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
           

解題思路:從後删減比對

執行用時 :1 ms, 在所有 Java 送出中擊敗了78.52%的使用者

記憶體消耗 :37.5 MB, 在所有 Java 送出中擊敗了52.50%的使用者

package com.lecode;

import java.util.HashMap;

/**
 * @Auther: DarkKing
 * @Date: 2020/06/04 18:53
 * @Description:
 */
public class LeetCode14{

   static class Solution {
        public String longestCommonPrefix(String[] strs) {
            if(strs==null||strs.length==0){
                return "";
            }
            String str = strs[0];
            for (String s : strs) {
                while (!s.startsWith(str)){
                    if(str.length()==1){
                        return "";
                    }
                }
                str = str.substring(0,str.length()-1);
            }
            return str;
        }

    }


}