1. 程式人生 > >公共項查詢---03_兩個陣列查詢子字串

公共項查詢---03_兩個陣列查詢子字串


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var arr_str = ['asdshowccccc','ddshoweeasd'];    // dshow
    function find(arr) {
        // 第一陣列
        let arr0 = arr_str[0];
        // 第二個陣列
let arr1 = arr_str[1]; // 最長字串的長度 let length = 0; // 最長字串的在arr0中的索引 let index = 0; // 遍歷 for ( let i = 0; i < arr0.length; i++ ) { for ( let j = 0; j < arr1.length; j++ ) { // 如果第一個字串的某一項 === 第二個字串的某一項 if ( arr0.charAt(i) === arr1.charAt(j) ){ let
k = 1; // 繼續比較下面的 while( arr0.charAt(i + k) === arr1.charAt(j + k)) { k++; // 找到最長的子字串 if ( k > length ) { // 長度 length = k; // 開始索引
index = i; } } } } } return arr0.substr(index, length); } console.log(find(arr_str));
</script> </body> </html>