字符串匹配问题

问题描述:
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.
给定一个字符串,只包含字符“(”、“””、“{”、“}”、“[”和“”),确定输入字符串是否有效。
括号必须以正确的顺序关闭,“()”和“()”{“}”都是有效的,但“()和[([ ] ] ] ]不是。


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

你可能感兴趣的:(javascript)