字符串匹配问题

来源:互联网 发布:大数据时代来临 编辑:程序博客网 时间:2024/05/21 17:46

问题描述:
Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.
给定一个字符串,只包含字符“(”、“””、“{”、“}”、“[”和“”),确定输入字符串是否有效。
括号必须以正确的顺序关闭,“()”和“()”{“}”都是有效的,但“()和[([ ] ] ] ]不是。

<!DOCTYPE html><html><head>    <meta charset="utf-8">    <title></title></head><body><script type="text/javascript">var isValid = function isValid(s) {    debugger    var valid = true,    pair = {        '(': ')',        '[': ']',        '{': '}'    },    nowWaitingFor = [];    for (var i = 0; i < s.length; i++) {        var nowChar = s.charAt(i);        if (nowChar.match(/[(\[\{]/)) {            nowWaitingFor.unshift(pair[nowChar]);        }         else if (nowChar.match(/[)\]\}]/)) {            if (nowWaitingFor[0] !== nowChar) {                valid = false;                break;            } else {                nowWaitingFor.splice(0, 1);            }        }    }    if (nowWaitingFor.length !== 0) {         valid = false;    }    return valid;};console.log(isValid("()})"))</script></body></html>