让我们假设我有两个字符串。在我的情况下,字符串为“ stringA”和“ stringB”:
示例1:
let stringA = "1ABC DEFGHI";
let stringB = "XYZABC DEFGHI";
即使两个字符串不完全相同,它们仍然包含大量字母序列,两者相同。在上述情况下,两个字符串中都出现了字符串"ABC DEFGHI"
。
示例2:这是另一个示例:
let stringA = "0142 41193566"
let stringB = "+49 142 41193566"
在这种情况下,结果应该为142 41193566
,因为这两个字符串都出现在这两个字符串中。
我会将该操作描述为种屏蔽操作,但是到目前为止,我在实现它方面尚未取得任何进展。不幸的是,到目前为止,我可以提供所有代码。
let stringA = "0142 41193566"
let stringB = "+49 142 41193566"
let stringC = "....ThISisATest"
let stringD = "+Th.ISisATest33"
let detectBiggestOccurrence = function(stringA, stringB) {
let result = []
for (let c in stringA) {
if (stringB.includes(stringA[c])) {
let index = stringB.indexOf(stringA[c])
result+=stringB[index]
}
}; return result
}
let resultWorking = detectBiggestOccurrence(stringA, stringB)
console.log("working:", resultWorking)
let resultNotWorking = detectBiggestOccurrence(stringC, stringD)
console.log("not working:", resultNotWorking)
问题:上面的代码适用于第一个调用(detectBiggestOccurrence(stringA, stringB)
),但不适用于第二个调用(detectBiggestOccurrence(stringC, stringD)
)。
答案 0 :(得分:2)
我用来解决您的问题的方法:
function detectBiggestOccurrence(stringA, stringB){
var mask ="";
var response ="";
stringA.split('').forEach( el => {
mask +=el;
if(stringB.includes(mask)){
if(mask.length > response.length){ response = mask; }
}
else {
mask =el;
}
})
return response;
}
let stringA = "1ABC DEFGHI";
let stringB = "XYZABC DEFGHI";
console.log(detectBiggestOccurrence(stringA, stringB));
let stringC = "0142 41193566";
let stringD = "+49 142 41193566";
console.log(detectBiggestOccurrence(stringC, stringD));
let stringE = "....ThISisATest"
let stringF = "+Th.ISisATest33"
console.log(detectBiggestOccurrence(stringE, stringF));
答案 1 :(得分:0)
这里是Pierre Capo的答案的修改版本。即使应该测试“有问题的”字符串,它也会返回正确的结果(请参阅我在Pierre的回答下的评论)。
function maxmatch(a,b){
var i=0,res='',pat=a[i];
while (i<a.length) {
if (b.includes(pat)) {
if (pat.length>res.length) res=pat;
pat+=a[++i];
}
else {
if (pat.length>1) pat=pat.slice(1);
else pat=a[++i];
}
}
return res;
}
let testStrings=[["1ABC DEFGHI","XYZABC DEFGHI"],
["1ABC DEFGHI","XYZBC DEFGHI ABC"],
["0142 41193566","+49 142 41193566"],
["....ThISisATest","+Th.ISisATest33"]];
testStrings.forEach(t=>console.log(maxmatch(...t)))
应用于测试字符串时(请注意:我添加了第一个测试字符串的修改版本),它们都将返回正确的答案:
ABC DEFGHI
BC DEFGHI
142 41193566
ISisATest