Leetcode 20 有效的括号 C++实现

给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。 注意空字符串可被认为是有效字符串。

示例 1:

输入: “()” 输出: true 示例 2:

输入: “()[]{}” 输出: true 示例 3:

输入: “(]” 输出: false 示例 4:

输入: “([)]” 输出: false 示例 5:

输入: “{[]}” 输出: true

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

自定义数组,用时0ms

class Solution {
    template<typename T>
class Array
{
public:
	Array(int capacity){
    	data = new T[capacity];
	size = 0;
	this->capacity = capacity;
    }
	Array(){
	this->capacity = 20;
	data = new T[capacity];
	size = 0;
    }
	T& operator[](int i){
    return data[i];}

	bool IsEmpty(){
    return size == 0;}

	void add(int index, T e){
    	if (size == capacity) {
			reSize(this->capacity * 2);
	}
	if (index<0 || index>size) {
		throw "add::index<0 || index>size";
	}
	for (int i = size - 1; i >= index; i--) {
		data[i + 1] = data[i];
	}
	data[index] = e;
	size++;
    }
    T remove(int index) {
	if (index<0 || index>size) {
		throw "remove::index<0 || index>size";
	}
	int ret = data[index];
	for (int i = index + 1; i < size; i++) {
		data[i - 1] = data[i];
	}
	size--;
	data[size] = NULL;
	if (size == capacity / 4 && this->capacity / 2 != 0)
	{
		reSize(this->capacity / 2);
	}
	return ret;}


	void AddLast(T e){
    add(size, e);}

	T removeLast(){
    return remove(size - 1);}

	~Array(){
        	if (data != NULL) {
       delete[] data;
	   data = NULL;
	}
    }

private:
	void reSize(int newcapacity){
    	T* newdata = new T[newcapacity];
	for (int i = 0; i < size; i++) {
		newdata[i] = data[i];
	}
	data = newdata;
	this->capacity = newcapacity;}
protected:

private:
	int size;
	T *data;
	int capacity;
};

template<typename T>
class ArrayStack
{
public:
	ArrayStack(){
    }
	bool IsEmpty(){
    return array.IsEmpty();}
	void Push(T e){
    array.AddLast(e);}
	T pop(){
    return array.removeLast();}

private:
	Array<T> array;
};

    
public:
	bool isValid(string s) {
		ArrayStack<char> mystack;
		for (unsigned int i = 0; i < s.length(); i++) {
			char ch = s[i];
			if (ch == '(' || ch == '[' || ch == '{') {
				mystack.Push(ch);
			}
			else {
				if (mystack.IsEmpty()) {
					return false;
				}
				char topch = mystack.pop();
				if (ch == ')'&&topch != '(') {
					return false;
				}
				if (ch == ']'&&topch != '[') {
					return false;
				}
				if (ch == '}'&&topch != '{') {
					return false;
				}
			}
		}
		return mystack.IsEmpty();
	}
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值