javascript 判斷括號是否配對。

wenlong_15發表於2020-12-07
示例::
		"()" | "()[]{}" | "{[]}"	true	{{{{}}}([])}
		"(]" | "([)]"	false				{{{{}}}([[])]}	{([)]}
		*/
		var str = "{{{{}}}([[])]}";
		var isValid = function(s){
			let items = []
			let sLength = s.length
			if(sLength % 2 !== 0){
				return false
			}
			for(let i=0; i < sLength; i++){
				switch(s[i]){
					case "(":
						items.push(s[i])
						break
					case "[":
						items.push(s[i])
						break
					case "{":
						items.push(s[i])
						break
					case ")":
						if(items[items.length - 1] === "("){
							items.pop()
						}
						break
					case "]":
						if(items[items.length - 1] === "["){
							items.pop()
						}
						break
					case "}":
						if(items[items.length - 1] === "{"){
							items.pop()
						}
						break
				}
			}
			return items.length === 0
		}
		console.log(isValid(str))

 

相關文章