网站游戏网站怎么做,北京南昌企业网站制作,设置网站默认编码,杭州上城区建设局网站文章目录1.题目详情2.代码详情1.题目详情
给定一个只包括 ‘(’#xff0c;’)’#xff0c;’{’#xff0c;’}’#xff0c;’[’#xff0c;’]’ 的字符串#xff0c;判断字符串是否有效。有效字符串需满足#xff1a;
左括号必须用相同类型的右括号闭合。 左括号…
文章目录1.题目详情2.代码详情1.题目详情
给定一个只包括 ‘(’’)’’{’’}’’[’’]’ 的字符串判断字符串是否有效。有效字符串需满足
左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。 注意空字符串可被认为是有效字符串。
示例 1: 输入: “()” 输出: true
示例 2: 输入: “()[]{}” 输出: true
示例 3: 输入: “(]” 输出: false
2.代码详情
python
class Solution(object):def isValid(self, s):stack []mapping {): (, }: {, ]: [}for char in s:if char in mapping:top_element stack.pop() if stack else #if mapping[char] ! top_element:return Falseelse:stack.append(char)return not stackjava
class Solution {private HashMapCharacter, Character mappings;public Solution() {this.mappings new HashMapCharacter, Character();this.mappings.put(), ();this.mappings.put(}, {);this.mappings.put(], [);}public boolean isValid(String s) {StackCharacter stack new StackCharacter();for (int i 0; i s.length(); i) {char c s.charAt(i);if (this.mappings.containsKey(c)) {char topElement stack.empty() ? # : stack.pop();if (topElement ! this.mappings.get(c)) {return false;}} else {stack.push(c);}}return stack.isEmpty();}
}