问题
guys! I want to ask you how can a make a function, that checks if the brackets in a string are put correctly. For example "(a + b).4,2 - )c + 5)" and I have to check the brackets. I tried something, but it doesn't seem to work(sorry, I'm a newbie in javascript):
function checkBrackets(str){
var newOrder = [];
var bracket1 = "(";
var bracket2 = ")";
for(var bracket1 in str){
newOrder.push("1");
}
for(bracket2 in str){
newOrder.pop();
}
if(newOrder.length == 0){
console.log("Right!" + newOrder);
} else{
console.log("Wrong!" + newOrder);
}
}
checkBrackets('( ( a + b ) / 5 – d )');
I tried to loop through the string with a for-in loop and whenever it hits a "(" to add "1" to the array. And when it hits a ")" to remove one "1" from the array. At the end if the array is empty, i could conclude, that the brackets were put correctly and if not, they weren't.
回答1:
You can do it this way :
// str is the string to parse
function checkBrackets(str){
// depth of the parenthesis
// ex : ( 1 ( 2 ) ( 2 ( 3 ) ) )
var depth = 0;
// for each char in the string : 2 cases
for(var i in str){
if(str[i] == '('){
// if the char is an opening parenthesis then we increase the depth
depth ++;
} else if(str[i] == ')') {
// if the char is an closing parenthesis then we decrease the depth
depth --;
}
// if the depth is negative we have a closing parenthesis
// before any matching opening parenthesis
if (depth < 0) return false;
}
// If the depth is not null then a closing parenthesis is missing
if(depth > 0) return false;
// OK !
return true;
}
console.log(checkBrackets('( ( a + b ) / 5 – d )')); // true
console.log(checkBrackets('( ( ) a + b ) / 5 – d )')); // false
console.log(checkBrackets('( ) ) ( ( a + b ) / 5 – d )')); // false
回答2:
While you've accepted an answer already, I felt it was a little complex, so I thought I'd expand on the naive solution I presented in the comments to the question:
function checkBrackets(str) {
// using a regular expression to find the number '(' characters in the string,
// escaping with a '\' because '(' is a special character within a regular
// expression; if no matches are found, and the result of 'match()' is falsey,
// we instead assign an empty array (in order that calling 'length', later, on
// a potentially-null object, won't create an error):
var opens = str.match(/\(/g) || [],
closes = str.match(/\)/g) || [];
// if there are equal numbers of '(' and ')' characters, we return true,
// otherwise false:
return opens.length === closes.length;
}
// unnecessary, this is just a means of iterating over the <li> elements, to work on
// a range of inputs for the function:
Array.prototype.forEach.call(document.getElementsByTagName('li'), function(li) {
// li is the <li> element/node itself, li.textContent is the text contained within
// that <li>, using the classList API to add a 'valid' class (if brackets are balanced)
// or an 'invalid' class (if the brackets are not balanced):
li.classList.add(checkBrackets(li.textContent) ? 'valid' : 'invalid');
});
ul {
margin: 0;
padding: 0;
}
li {
list-style-type: none;
margin: 0 0 0.5em 0;
padding: 0.5em;
width: 100%;
box-sizing: border-box;
}
.valid {
border: 1px solid #0f0;
}
.invalid {
border: 1px solid #f00;
}
<ul>
<li>( ( a + b ) / 5 - d )</li>
<li>( a + b ) / 5 - d</li>
<li>( a + b ) / ( 5 - d )</li>
<li>( a + b ) / 5 - d )</li>
<li>a + b ) / 5 - d</li>
<li>( a + b / 5 - d</li>
</ul>
References:
- Array.prototype.forEach().
- Element.classList.
- Function.prototype.call().
- JavaScript Regular Expressions.
- String.prototype.match().
回答3:
Here's how I would do it to handle not just parentheses but other characters as well. If it's more than just parentheses you need to validate, then you need to implement a stack/array. You can also use the length of the stack instead of declaring a balance/depth/count variable.
function IsValid(text) {
let leftBraces = [];
let RightBrace = c => {
switch (c) {
case ')': case '}': case ']':
return true;
case '(': case '{': case '[':
leftBraces.push(c);
default:
return false;
}
};
for (let i = 0; i < text.length; i++) {
let e = text[i];
if (RightBrace(e) && !Match(leftBraces.pop() + e))
return false;
}
return leftBraces.length === 0;
}
function Match(t) {
switch (t) {
case '()': case '{}': case '[]':
return true;
default:
return false;
}
}
console.log(IsValid('c[d]')) // true
console.log(IsValid('a{b[c]d}e')) // true
console.log(IsValid('a{b(c]d}e')) // false - ] doesn’t match (
console.log(IsValid('a[b{c}d]e}')) // false - nothing matches final }
console.log(IsValid('a{b(c)')) // false - no matching }
来源:https://stackoverflow.com/questions/27582160/js-function-for-validation-of-the-brackets-in-a-string