1. 程式人生 > 其它 >[LeetCode] #14 最長公共字首

[LeetCode] #14 最長公共字首

[LeetCode] #14 最長公共字首

編寫一個函式來查詢字串陣列中的最長公共字首。

如果不存在公共字首,返回空字串""

輸入:strs = ["flower","flow","flight"]

輸出:"fl"

暴力解法,拿字串陣列的第一個字串中的第一個字元作為比對字首,利用startsWith(prefix)看後面所有字串是否有該字首,都有的話比對字首繼續往後取,有一個沒有就結束迴圈。

class Solution {
    public String longestCommonPrefix(String[] strs) {

        if(strs == null || strs.length == 0) return
""; String pre = ""; for(int len = 1; len <= strs[0].length(); len++){ pre = strs[0].substring(0,len); for(int i = 1; i < strs.length; i++) if(!strs[i].startsWith(pre)) return pre.substring(0,pre.length()-1); } return pre; } }

看別人的解法,直接取第一個字串作為字首和其他字串比,不能作為字首就縮短,繼續看是不是字首。

這種解法秒就秒在與前幾個字串比對後就已經將比對字首縮短到了一定程度,使得後面比對次數大幅減少。

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

知識點:

boolean startsWith(String pre)方法一般用於檢測某請求字串是否以指定的字首開始的。

與之相對應的方法為endsWith() ,用來判斷字串結尾的字尾。

substring() 方法返回字串的子字串。

public String substring(int beginIndex) public String substring(int beginIndex, int endIndex)

  • beginIndex -- 起始索引(包括), 索引從 0 開始。

  • endIndex -- 結束索引(不包括)。

總結:有的時候,可以嘗試逆向思維,比如找字首不一定從空串開始累加,可以從一個完整字串遞減。