简体   繁体   中英

check if both sides of the string are equal in javascript

I want to write a function to test if a string such as "(())" or "<<>>" is equal on both sides if they were reversed. where as something like "((()" would be false

Is there a name for something like this? I assume is a common algorithm.

For some reason, reverse doesn't do anything on right after splitting it into an array?

 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("(())") 

Store the opposites in an object. There is no other way to determine that < is an opposite of > etc. Then run your string through a function that takes half of your string and checks if the other half (in correct order) is made up of its opposites. Note that below solution works if length is even.

 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("(())")); 

 const REVERSED = { "(": ")", "<": ">", "[": "]", } function ifEqual(str) { let left = str.slice(0, str.length / 2).split(''); let right = str.slice(str.length / 2, str.length).split(''); return left.every((next, index) => REVERSED[next] == right[right.length - index - 1]) } console.log(ifEqual("(())")) console.log(ifEqual("<(>>")) console.log(ifEqual("<[[(())]]>")) 

Perhaps you're looking for balanced parenthesis

 var balancedParens = function(str) { var stack = []; var open = { '{': '}', '[': ']', '(': ')' }; var closed = { '}': true, ']': true, ')': true }; for (var i = 0; i < str.length; i ++) { var chr = str[i]; if (open[chr]) { stack.push(chr); } else if (closed[chr]) { if (open[stack.pop()] !== chr) return false; } } return stack.length === 0; }; 

https://medium.com/@robhitt/balance-parenthesis-in-javascript-60f451a00c4c

(()) is not a palindrome, no matter how symmetrical it may look. Don't let the optical illusion deceive you. Bellow is a common implementation of the palindrome checker algorithm in JavaScript.

 function ifEqual(str) { return str === str.split("").reverse().join("") } console.log(ifEqual("(())")) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM