用于验证字符串中的方括号

用于验证字符串中的方括号

本文介绍了JS函数,用于验证字符串中的方括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们!我想问你一个函数如何检查字符串中的括号是否正确放置.例如((a + b).4,2-)c + 5)",我必须检查方括号.我尝试了一些方法,但是似乎没有用(对不起,我是javascript新手):

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 )');

我尝试使用for-in循环遍历字符串,只要它在命中("时就向数组添加"1".当它命中)"时就从数组中删除一个"1" .最后,如果数组为空,我可以得出结论,正确放置了括号,否则,不是.

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.

推荐答案

您可以这样做:

// 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

这篇关于JS函数,用于验证字符串中的方括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 12:54