1. 程式人生 > >leetcode記錄:難度簡單:14. 最長相同字首

leetcode記錄:難度簡單:14. 最長相同字首

題目出處:https://leetcode.com/problems/longest-common-prefix/

題目描述:

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

如果沒有公共字首,則返回空字串“”。

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

 

程式碼:

/**
     * @param {string[]} strs array
     * @return {string}
     */
    var longestCommonPrefix = function(strs) {
        var result = [];
        var jiequshuzi;
        //將每一個元素從首字母開始遍歷後的結果拼接
        strs.reduce(function (pre, cur) {
            // console.log(cur);
            for (var i in cur){
                if (pre[i] == cur[i]){
                    result.push(pre[i])
                }else {
                    break
                }
            }
            // console.log(result);
            return result
        });

        //最後一個首字母的下標之後的值,就是結果
        result = result.join('');
        console.log(result);

        //獲取最後一個首字母的下標
        jiequshuzi = result.lastIndexOf(result[0]);

        //檢視結果
        console.log(result.substring(jiequshuzi));
        return result.substring(jiequshuzi)
    };


    var ary = ["flower","flow","flight","fluw"];
    var ary1 = ["teacher","tea","tektic","tecnology"];
    var ary2 = ["dog","racecer","car"];
    longestCommonPrefix(ary)    //fl
    longestCommonPrefix(ary1)   //te
    longestCommonPrefix(ary2)   //

但是:

leetcode的檢測結果沒過,報錯資訊:reduce函式需要一個初始值。

看了solution之後修改:

var longestCommonPrefix = function (strs) {
        if (strs.length == 0) return "";
        var prefix = strs[0];
        for (var i = 1; i<strs.length; i++) {
            while (strs[i].indexOf(prefix) != 0) {
                prefix = prefix.substring(0, prefix.length - 1);
                if (prefix.length == 0) return "";
            }
        }
        return prefix
    };

筆記:

1.splice方法用於陣列,substring,substr方法用於字串,後2者的區別在於第二個引數,一個表示擷取長度,一個表示擷取結束位置。

2.reduce這個方法的初始值那個引數應該是可選的,是可以的不寫的(reduce相關,進去第3條