思路
题目链接:有效的括号
建立一个长度为0的切片t,让它模拟栈的操作。首先遍历s,如果遇到的字符c为(、[、{,便入栈。如果遇到)、]、},便检查t是否为空,再价差t尾部元素是否与c为一对,如果是一对,则删除最后该尾部元素;如果不是一对,则跳出循环,返回false。最后在循环完成之后检查t是否为空,确定最终结果。
Golang代码
func isValid(s string) bool {
f := true
t := make([]rune, 0)
for _, v := range s {
if v == '(' || v == '[' || v == '{' {
t = append(t, v)
continue
}
// example "]"
if len(t) == 0 {
f = false
break
}
if v == ')' {
if t[len(t)-1] != '(' {
f = false
break
}
}
if v == ']' {
if t[len(t)-1] != '[' {
f = false
break
}
}
if v == '}' {
if t[len(t)-1] != '{' {
f = false
break
}
}
t = t[:len(t)-1]
}
if len(t) > 0 {
f = false
}
return f
}
C++代码
bool judge(char c, stack<char> &st){
if(st.empty()){
return false;
}
if(c == ')' && st.top() != '('){
return false;
}else if(c == ']' && st.top() != '['){
return false;
}else if(c == '}' && st.top() != '{'){
return false;
}
return true;
}
class Solution {
public:
bool isValid(string s) {
bool f = true;
stack<char> st;
for(char c : s){
if(c == '(' || c == '[' || c == '{'){
st.emplace(c);
}else if(judge(c, st)){
st.pop();
continue;
}else{
f = false;
break;
}
}
if(!st.empty()){
f = false;
}
return f;
}
};