javascript实现:在N个字符串中找出最长的公子串

2018-11-12 06:50:42来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

 

 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 }

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:React之设置元素的滚动条

下一篇:visual studio2017 创建Vue项目