1 'use strict' 2 3 function 找出最長公子串 (...strings) { 4 let arraiesOfSubStrings = [] 5 arrayOfStrings.reduce((accumulator, currentValue) => { 6 arraiesOf... ...
1 'use strict' 2 3 function 找出最長公子串 (...strings) { 4 let arraiesOfSubStrings = [] 5 arrayOfStrings.reduce((accumulator, currentValue) => { 6 arraiesOfSubStrings.push(findAllSubStringsFromTwoString(accumulator, currentValue)) 7 return accumulator 8 }) 9 return findTheLongest(findIntersection(...arraiesOfSubStrings)) 10 } 11 12 function findIntersection (...sets) { 13 /** 14 * 15 * 16 * @param {sets} a list of sets 17 * @returns {array} the elements of the intersection of given sets. 18 */ 19 return sets.reduce((accumulator, currentValue) => [...accumulator].filter(value => currentValue.has(value))) 20 } 21 22 function findAllSubStringsFromTwoString (string1, string2) { 23 let string = string1.split(''), 24 nextString = string2.split(''), 25 currentSubString, 26 subStrings = new Set(), 27 nextFindStartPoint 28 for (let i_string = 0; i_string < string.length; i_string++) { 29 let character = string[i_string] 30 if (nextFindStartPoint === undefined) { 31 nextFindStartPoint = nextString.findIndex(function getIndexOfFirstFindedElement (element, index, array) { 32 return element === character 33 }) 34 if (nextString[nextFindStartPoint] === character) { 35 currentSubString = currentSubString ? currentSubString + character : character 36 subStrings.add(currentSubString) 37 } 38 nextFindStartPoint = nextFindStartPoint === -1 ? undefined : nextFindStartPoint 39 } else { 40 if (nextString[nextFindStartPoint + 1] === character) { 41 nextFindStartPoint = nextFindStartPoint + 1 42 currentSubString = currentSubString ? currentSubString + character : character 43 } else { 44 nextFindStartPoint = undefined 45 subStrings.add(currentSubString) 46 currentSubString = character 47 } 48 } 49 } 50 return subStrings 51 } 52 53 function findTheLongest (arrayOfStrings) { 54 return arrayOfStrings.reduce((accumulator, currentValue) => findTheLonger(accumulator, currentValue), '') 55 56 function findTheLonger (string1, string2) { 57 return (string1.length > string2.length) ? (string1) : (string2) 58 } 59 }