JS函数用于验证字符串中的括号

时间:2014-12-20 16:31:48

标签: javascript arrays numbers expression brackets

家伙!我想问你如何创建一个函数,检查字符串中的括号是否正确放置。例如“(a + b).4,2 - )c + 5)”,我必须检查括号。我尝试了一些东西,但它似乎没有用(对不起,我是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” 。最后,如果数组是空的,我可以得出结论,括号被正确放置,如果没有,它们不是。

3 个答案:

答案 0 :(得分:4)

你可以这样做:

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

答案 1 :(得分:1)

虽然你已经接受了答案,但我觉得这有点复杂,所以我想我会扩展我在评论中提出的天真解决方案:

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>

参考文献:

答案 2 :(得分:0)

在这里,我不仅要处理括号,还要处理其他字符。如果不仅需要括号,还需要进行验证,则需要实现一个堆栈/数组。您也可以使用堆栈的长度,而不用声明平衡/深度/计数变量。

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 }