我想编写一个函数来测试“(())”或“<<>>”等字符串反转后两边是否相等。像“((()”这样的东西是错误的
类似的东西有名字吗?我认为这是一种常见的算法。
出于某种原因,reverse 在将其拆分为数组后不会立即执行任何操作?
function ifEqual(str) {
let left = str.slice(0, str.length / 2);
let right = str.slice(str.length / 2).split("").reverse().join("");
console.log(left);
console.log(right);
return left === right;
}
ifEqual("(())")
最佳答案
将相反数存储在一个对象中。没有其他方法可以确定 <
是 >
的反义词然后通过一个函数运行您的字符串,该函数接受字符串的一半,并检查另一半(按正确的顺序)是否由其相反的部分组成。请注意,如果长度为偶数,则以下解决方案有效。
const opposites = {
"(": ")",
")": "(",
"<": ">",
">": "<",
"[": "]",
"]": "["
};
function isMirrored(str) {
const half = str.slice(0, str.length / 2);
const reversed = half.split("").reverse().join("");
let mirrored = half;
for(char of reversed) {
mirrored += opposites[char];
}
return str === mirrored;
}
console.log(isMirrored("[[]]"));
console.log(isMirrored("<<>>"));
console.log(isMirrored("<()>"));
console.log(isMirrored("([]("));
console.log(isMirrored("(())"));
关于javascript - 在javascript中检查字符串两边是否相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51830448/