笔试代码题--小米2020--有效的括号匹配

笔试代码题--小米2020--有效的括号匹配


题目描述

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

有效字符串需满足:

    左括号必须用相同类型的右括号闭合。
    左括号必须以正确的顺序闭合。

注意空字符串可被认为是有效字符串。

示例 1:

输入: "()"
输出: true

示例 2:

输入: "([)]"
输出: false

示例 3:

输入: "{[]}"
输出: true

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses

代码如下,思路:先建立栈,然后遍历字符串,判断栈顶和str[i]符合括号的条件不,如果符合,栈顶pop出去,继续循环判断,如果不符合,将str[i]的值push进去。如果最后栈是空的就是有效符号。

#include <iostream>
#include <stack>
#include <vector>
#include <string>
#include <unordered_map>
using namespace std;
//匹配括号   {([])}   {}   ()  []

bool Istring(string vec)
{
	int size = vec.size();
	if(vec.empty())
	{
		return true;
	}
	if(size % 2 == 1)
	{
		return false;
	}
	stack<char> stack1;
	//建立栈,判断栈顶和栈str[i]符合括号不,如果符合,栈顶pop出去,继续循环判断,如果不符合,将str[i]的值push进去。
	
	for(int i = 0 ; i < size; i ++)
	{
		string str = vec;
		if(!stack1.empty() &&( (stack1.top() == '(') && (str[i]==')') || (stack1.top() == '[') && (str[i]==']') ||(stack1.top() == '{') && (str[i]=='}')))
		{
			stack1.pop();
		}
		else
		{
			stack1.push(str[i]);
		}
	}
	return stack1.empty();
    }
	/*
	//思路是一样的,只是用了unorder_map来查找另一半括号
	if(vec.empty())
	{
		return true;
	}
	int size_vec = vec.size();
	if(size_vec % 2 == 1)
	{
		return false;
	}

	std::unordered_map<char,char> map1 = { { ')', '(' }, { ']', '[' }, { '}', '{' }};

	stack<char> stack1;
	for(char c : vec)
	{
		if(map1.count(c))//map1.count(ch) != 0 代表ch存在
		{
		if(stack1.empty()|| stack1.top() != map1[c])//找到ch后,判断栈顶是否匹配
			return false;
		stack1.pop();
		}
		else
		{
			stack1.push(c);
		}
	}
    return stack1.empty();
    }
*/
int main()
{
	string str ;
	
	while(cin >> str)
	{
		if(Istring(str))
		{
			cout <<  true <<endl;
		}
		else
		{
			cout <<  false <<endl;
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41103495/article/details/108625131