假设我们正在比较两个字符串,这两个字符串有一个特殊的字符,在这种情况下会导致一些不寻常的事情发生
#
character删除前一个字符。
这里有一个解决方案,它构建字符串,然后使用字符串方法对它们进行比较
slice
和
concat
:
const checkSame = (a, b) => {
let one = ''
for(let i = 0; i < a.length; i++){
if(a[i] === '#'){
one.slice(0, -1)
} else {
one.concat(a[i]);
}
}
let two = ''
for(let i = 0; i < b.length; i++){
if(b[i] === '#'){
one.slice(0, -1)
} else {
one.concat(b[i]);
}
}
return one === two
};
这是另一种使用数组及其方法的解决方案
push
和
pop
:
export const compareTwoStrings2 = (a, b) => {
let one = [];
for (let i = 0; i < a.length; i++) {
if (a[i] === "#") {
one.pop();
} else {
one.push(a[i]);
}
}
let two = [];
for (let i = 0; i < b.length; i++) {
if (b[i] === "#") {
two.pop();
} else {
two.push(b[i]);
}
}
for(let i = 0; i < one.length; i++){
if(one[i] !== two[i]) return false;
}
return true;
};
第二种解决方案使用了一个额外的循环,这让我认为,如果给定一个字符串
n
它需要的角色
O(3n)
时间(最坏的情况),第一种情况只需要
O(2n)
时间。
这是正确的吗?连接和切割字符串比使用数组更有效吗?或者,这两个字符串的最终比较是否也需要
n
随着琴弦长度的增加,时间会变长吗?