You are given two strings. In a single move, you can choose any of them, and delete the first (i.e. leftmost) character.
For Example:
By applying a move to the string "where", the result is the string "here". By applying a move to the string "a", the result is an empty string "". Implement a function that calculates the minimum number of moves that should be performed to make the given strings equal.
Notes:
Both strings consist of lowercase latin letters. If the string is already empty, you cannot perform any more delete operations.
我的问题是,我假设您需要循环遍历两个字符串才能继续比较它们是否相等。如果它们不相等,则增加计数器并再次循环。
但我不确定我是否正确地同时循环了两个字符串。
是i < (s.length, t.length);
正确的语法?
这是我尝试过的:
function shiftLeft(s, t) {
let sArray = s.split("");
let tArray = t.split("");
let counter = 0;
for (let i = 0; i < Math.min(s.length, t.length); i++) {
if (s === t) {
return counter;
}
if (s !== t && s.length > t.length) {
sArray.shift("");
counter += 1;
}
if (s !== t && t.length > s.length) {
tArray.shift("");
counter += 1;
}
if (s !== t && t.length === s.length) {
sArray.shift("");
tArray.shift("");
counter += 1;
}
}
return counter;
}
console.log(shiftLeft("west", "test"));
但是它给了我一个错误的测试值 - "test"
的计数器和"west"
应该只等于 2,而这将返回 4。
是我的逻辑错误还是for循环的语法错误,或者两者兼而有之?
最佳答案
您的代码存在一个问题,即在每次迭代结束时,您都会更新 sArray
和 tArray
,而不更新 s
和 t
.
然后,在下一次迭代中,您将检查 s 和 t 是否相等,但情况永远不会如此,除非它们从一开始就相等。
因此,您也应该更新 s
和 t
。
此外,在这部分代码中:
if (s !== t && t.length === s.length) {
sArray.shift("");
tArray.shift("");
counter += 1;
}
计数器不应该加2吗? (我认为这是两个步骤,但这取决于您)。
<小时/>顺便说一句,使用 s = s.substring(1);
删除第一个字符应该比处理数组更简单......
下面是使用您自己的逻辑的片段,但解决了我上面提到的问题。希望这有帮助!
function shiftLeft(s, t) {
let counter = 0;
while(Math.min(s.length, t.length) > 0) {
if (s === t) {
return counter;
}
if (s !== t && s.length > t.length) {
s = s.substring(1);
counter += 1;
}
if (s !== t && t.length > s.length) {
t = t.substring(1);
counter += 1;
}
if (s !== t && t.length === s.length) {
s = s.substring(1);
t = t.substring(1);
counter += 2; //shouldn't this be 2 instead of 1?
}
}
return counter;
}
console.log(shiftLeft("test", "yes"));
编辑:事实证明您的 for 循环条件不正确。计数器 i
不断增加,而 Math.min(s.length, t.length)
不断减少并接近零,因此循环会过早停止。我们想要的真正逻辑是继续循环,直到其中一个字符串变空。
关于JavaScript - 比较字符串并从其中一个字符串中删除第一个字符,直到它们相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56030119/