题目描述:
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:左括号必须用相同类型的右括号闭合。左括号必须以正确的顺序闭合。每个右括号都有一个对应的相同类型的左括号。
学习记录:
最开始的想法就是,定义三个计数的变量a,b,c,分别记录(),{},[],的个数,左加右减,过程中不小于0,最后等于0是正确的。但是存在一种情况 ( [ ) ] 这种情况在我的方法中会返回正确,但是显然这个应该是不正确的,因此wrong!
题解:栈的方法,栈与含括号是的方式是完全一样的!非常nice,自己写了下代码:
一些重要的注意点都写在注释里了,注意条件的判断,特别注意情况s=" ] [ "
class Solution {
public:
bool isValid(string s) {
stack<char> judge;
int length=s.length();
if(length%2==1) //奇数可以直接run
return false;
for(int i=0;i<length;i++)
{
if( s[i]=='(' || s[i]=='{' || s[i]=='[' )
judge.push(s[i]);
else
{
//注意情况s="]["此时栈为空,不能直接求top
if(judge.empty())
return false;
char temp=judge.top();
if( s[i]==')'&&temp!='(' )
return false;
if( s[i]==']'&&temp!='[' )
return false;
if( s[i]=='}'&&temp!='{' )
return false;
judge.pop();//注意这里需要出栈,不然后续判断空为错的
}
}
if(judge.empty())
return true;
else
return false;
//可改写为 return judge.empty();
}
};
题解里给出的代码用到了unordered_map,leetcode是真的喜欢用,也是真的方便,粘上来学习一下
class Solution {
public:
bool isValid(string s) {
int n = s.size();
if (n % 2 == 1) {
return false;
}
unordered_map<char, char> pairs = {
{')', '('},
{']', '['},
{'}', '{'}
};
stack<char> stk;
for (char ch: s) {
if (pairs.count(ch)) {
if (stk.empty() || stk.top() != pairs[ch]) {
return false;
}
stk.pop();
}
else {
stk.push(ch);
}
}
return stk.empty();
}
};
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/valid-parentheses/solution/you-xiao-de-gua-hao-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
unordered_map系统学习一下:
#include <iostream>
#include <string>
#include <unordered_set>
#include <unordered_map>
using namespace std;
int main()
{
unordered_map<char,char> t;
//增加元素的方式
//t.emplace('a','b');---这种可能在C++11中可以,这里报错,但看别人 is OK
//t.insert( { {'a','b'},{'c','d'} });---这种可能在C++11中可以,这里报错,但看别人 is OK
pair<char,char> temp('c','d'); t.insert(temp);
t['a']='b';
//一个key只有一个hash
t['a']='b'; t['a']='c';
cout<<t.at('a')<<endl;
//find和at的不同用法,find返回的是迭代器
auto it=t.find('a');
cout<<t.at('a')<<" "<<it->first<<" "<<it->second<<endl;
//count的用法,count(key)
cout<<t.count('a')<<" "<<t.count('b')<<endl;
//erase的用法--返回应该只有0和1吧
int delNum = t.erase('a'); int delNum2 = t.erase('x');
cout<<delNum<<" "<<delNum2<<endl;
system("pause");
return 0;
}
输出: