LeetCode Hot100 简单篇(2)—有效的括号

思路

题目链接:有效的括号

建立一个长度为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;

  }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值