在工作面试中,您面临挑战,要编写一种算法来检查给定的字符串s是否可以由其他两个字符串part1和part2组成。
At a job interview, you are challenged to write an algorithm to check if a given string, s, can be formed from two other strings, part1 and part2.
限制是第1部分和第2部分中的字符与s中的顺序相同。
The restriction is that the characters in part1 and part2 are in the same order as in s.
面试官给您以下示例,并告诉您找出其余示例
The interviewer gives you the following example and tells you to figure out the rest from the given test cases.
例如:
'codewars'是'cdw'和'ears':
'codewars' is a merge from 'cdw' and 'oears':
www.codewars/kata/merged-string-checker/train/javascript
下面是我的JavaScript代码,请输入需要帮助识别我的错误才能通过所有测试。谢谢!
Below is my javascript code,Please i need help to identify my mistakes to be able to pass all the tests.Thank you!
function isMerge(s, part1, part2) { var k = part1 + part2; for(var b = 0, len = s.length; b < len; b++) { for(var i = 0, len = k.length; i < len; i++) { if (s[b] === k[i]) { return true; } } } return false; }
推荐答案
我注意到了几件事,可能会使您按正确的方向进行操作:
Here are a couple of things that I noticed that may send you on the right track:
首先,您将part1与part2连接在一起。这将无法工作,因为如果您在所提供的示例中注意到, codewars是 cdw和 ears 的合并。简单地将 cdw 与 oears 连接起来就不够了,因为 cdwoears 不等于 codewars 。
First, you are concatenating part1 with part2. This wont work, since if you notice in the example you provided, "codewars" is a merge from "cdw" and "oears". Simply concatenating "cdw" with "oears" wont suffice, since "cdwoears" doesn't equal "codewars".
在示例中请注意,如果您检查part1 ( cdw )和part2( oears )依次,相对于输入字符串 s ,您最终可以拼出整个字符串( codewars )。为了澄清起见,请注意它们如何在Codewars问题中说明这一点:
Notice in the example that if you examine part1 ("cdw") and part2 ("oears") in order, character by character against the input string s, you can eventually spell out the whole string ("codewars"). To clarify, note how they illustrate this in the Codewars problem:
s: c o d e w a r s = codewars part1: c d w = cdw part2: o e a r s = oears一种方法可能是创建指向索引的指针您目前正在为part1和另一个为part2做准备。然后遍历输入字符串 s 并递增具有匹配字符的指针,如果没有匹配项,则返回false。
One approach could be to create a pointer to the index that you are currently up to for part1 and another for part2. Then iterate through the input string s and increment the pointer for which you have a matching character and just return false if you ever don't have a match.
更多推荐
合并Codewars中的字符串检查器
发布评论