[算法Rust,Go,Python,JS实现)]LeetCode之20-有效括号匹配
2019-03-14 10:44
821 查看
版权声明:未经博主允许不得转载(https://github.com/ai-word) https://blog.csdn.net/BaiHuaXiu123/article/details/88547680
题目
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 有效字符串需满足: 左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。 注意空字符串可被认为是有效字符串。 示例 1: 输入: "()" 输出: true 示例 2: 输入: "()[]{}" 输出: true 示例 3: 输入: "(]" 输出: false 示例 4: 输入: "([)]" 输出: false 示例 5: 输入: "{[]}" 输出: true
思路
利用栈的思想去解决 模拟stack,因此将字符串顺序读取一遍,要么入栈要么出栈,当出现左括号就入栈, 当出现右括号并且栈顶括号无法匹配成一对就入栈,当右括号可以和栈顶配对就把栈顶出栈。 一种特殊情况是,只有一个字符时比如’]‘,栈为空没有栈顶元素, 会报错超出索引范围,就随便用一个字符比如1,代替,最后跟这个字符进行比较就可以了,得到最终的结果
Rust语言实现
use std::collections::HashMap; impl Solution { pub fn is_valid(s: String) -> bool { let mut stack = vec!["1".to_string()]; let mut map = HashMap::new(); map.insert(String::from("{"),"}"); map.insert(String::from("["),"]"); map.insert(String::from("("),")"); for it in s.chars() { let c2s = it.to_string(); let ss = map.get(&c2s); if let Some(b) = ss{ stack.push(c2s.clone()); } else { let mut s1 = stack.pop().unwrap(); let s2 = map.get(&s1); if let Some(U) = s2{ if *U != c2s { return false; } } else { return false; } } } if stack.len()==1{ return true; } else { return false; } } }
Go语言
func isValid(s string) bool { stack := make([]byte, 0) for _, v := range s { if v == '[' || v == '(' || v == '{' { stack = append(stack, byte(v)) } else { if (len(stack) != 0 && match(stack[len(stack)-1], byte(v))) { stack = pop(stack) continue } else { return false } } } if (len(stack) == 0) { return true } else { return false } } func match(left, right byte) bool { switch right { case ']': if left != '[' { return false } case ')': if left != '(' { return false } case '}': if left != '{' { return false } } return true } func pop(stack []byte) []byte { return stack[:len(stack)-1] }
javaScript语言
var isValid = function(s) { if(s == null||s.length <1){ return true; } var stack = []; for(var i=0;i<s.length;i++){ if(s[i] == ""){ continue; } if(stack.leng<1){ stack.push(s[i]); }else if(stack[stack.length-1]=="("&&s[i]==")" ||stack[stack.length-1]=="{"&&s[i]=="}" ||stack[stack.length-1]=="["&&s[i]=="]"){ stack.pop(); }else{ stack.push(s[i]); } } return stack.length<1; };
python语言
class Solution: def isValid(self, s): stack = list(['1']) for st in s: if st in ['(', '[', '{']: stack.append(st) elif (stack[len(stack)-1]+st) not in ['()', '[]', '{}']: stack.append(st) else: stack.pop() if stack == ['1']: return True else: return False
结果
代码下载地址
相关文章推荐
- [算法Rust,Go,Python,JS实现)]LeetCode之53-最大子序和
- [算法Rust,Go,Python,JS实现)]LeetCode之26.-删除排序数组中的重复项
- [算法Rust,Go,Python,JS实现)]LeetCode之38-报数
- [算法Rust,Go,Python,JS实现)]LeetCode之21-合并两个有序链表
- [算法Rust,Go,Python,JS实现)]LeetCode之35-搜索插入位置
- [算法Rust,Go,Python,JS实现)]LeetCode之27-移除元素
- [leetcode]20. Valid Parentheses ,有效的括号符串python实现【easy】
- Leetcode刷题记——20. Valid Parentheses (有效的括号即括号匹配)
- 【LeetCode-面试算法经典-Java实现】【032-Longest Valid Parentheses(最长有效括号)】
- Leetcode做题日记:20. 有效的括号 (PYTHON)
- Leetcode20 python有效的括号
- 【刷算法】LeetCode.20-有效的括号
- LeetCode题解(python)-20. 有效的括号
- python实现leetcode-第20题-有效的括号
- 【LeetCode-面试算法经典-Java实现】【032-Longest Valid Parentheses(最长有效括号)】
- 数据结构13: 括号匹配算法及C语言实现
- 算法学习 - 括号匹配(栈实现)C++
- 用栈实现括号匹配的算法
- Leetcode 20 Valid Parentheses 判断括号匹配
- 【算法分析】如何理解快慢指针?判断linked list中是否有环、找到环的起始节点位置。以Leetcode 141. Linked List Cycle, 142. Linked List Cycle II 为例Python实现