[Codewars]-Longest Common Subsequence
题目:
- 编写一个函数LCS接受两个字符串,并返回传入的最长子字符串
- 题目的意思有点说不明白。我试着去解释下,就是要返回两个函数的共有的字符组成的字符串,而且是从左往右按顺序的。
- 举个例子:
finaltest zzzfinallyzzz
得返回final "anothertest", "notatest"
需要返回nottest
,而不包含a。
思路:
- 直接按照
y
元素出现顺序从左往右开始开始检索x
字符串,而且不回头地检索
解答:
- 私以为这个方法比较简洁漂亮
function LCS(x, y) {
var result = ''
var pos = 0
y.split('').forEach(function(a){
var newPos = x.indexOf(a,pos)
if(newPos >=0 ){
pos = newPos+1
result += a
}
})
return result
}