題目詳情:
編寫一(yi)個函數來查找字符串(chuan)數組中的(de)最長(chang)公共前(qian)綴。
如果不(bu)存在(zai)公共前綴,返回空字符串 ""。
示例:
輸入:strs = ["flower","flow","flight"]
輸出:"fl"
解題思路:
首先,我們檢查數組 strs 是(shi)否為空,如果是(shi),則直接返回空字符串(chuan)。
然(ran)后,我們(men)將數組中的第一個字(zi)符串作為初始的公共前(qian)綴 prefix。
接(jie)下來,使用一個循環遍歷數組中的其(qi)他字符(fu)串(chuan)。對于每個字符(fu)串(chuan),我們不斷地從 prefix 的末(mo)尾開始刪(shan)除字符(fu),直到其(qi)在當(dang)前(qian)字符(fu)串(chuan)中以該前(qian)綴開頭(即 strs[i].indexOf(prefix) === 0)。如果此時 prefix 變為空(kong)字符(fu)串(chuan),說明不存在公(gong)共(gong)前(qian)綴,直接(jie)返回空(kong)字符(fu)串(chuan)。
最后,返回公共前(qian)綴 prefix。
代碼實現:
function longestCommonPrefix(strs) {
if (strs.length === 0) {
return "";
}
let prefix = strs[0];
for (let i = 1; i < strs.length; i++) {
while (strs[i].indexOf(prefix) !== 0) {
prefix = prefix.slice(0, prefix.length - 1);
if (prefix === "") {
return "";
}
}
}
return prefix;
}
// 示例輸入
const strs = ["flower", "flow", "flight"];
// 調用函數并輸出結果
console.log(longestCommonPrefix(strs));