LeetCode 20題:括號匹配問題

問題描述

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

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.

翻譯:給定一個僅包含()[]{}的字符串,判斷輸入字符串是否合法;

當且僅當輸入字符串滿足以下條件時才合法:

  1. 括號由同類型括號閉合;
  2. 括號的閉合以正確的順序;

注意空字符串也是合法的;

實現原理

棧數據結構是後進先出的形式,可以滿足我們的需求;每次遇到左括號([{時進行入棧,然後遇到右括號)]}時進行出棧並判斷出棧元素是否與當前字符匹配,如果匹配成功則繼續;直至遍歷整個字符串;

遍歷結束後,如果棧爲空,則完全匹配,字符串合法;負責字符串不合法;

show you the code

// code source: https://yuchengkai.cn/docs/cs/dataStruct.html#%E5%AE%9E%E7%8E%B0
const isStrValid = s => {
	const map = {
		"(": -1,
		")": 1,
		"[": -2,
		"]": 2,
		"{": -3,
		"}": 3
	}
	let stack = [];
	for (let i = 0; i < s.length; i++) {
		if (map[s[i]] < 0) {
			stack.push(s[i]);
		} else {
			let top = stack.pop();
			if (map[top] + map[s[i] !== 0) {
				return false;
			}
		}
	}
	if (stack.length > 0) return false;
	return true;
}

參考文獻

  1. https://leetcode.com/problems/valid-parentheses/
  2. https://yuchengkai.cn/docs/cs/dataStruct.html#%E5%AE%9E%E7%8E%B0
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章