xxxxxxxxxx
class Solution {
public:
bool isValid(string s) {
stack<char>st;
if(s.length()==1)
return false;
for (int i = 0; i < s.length(); i++)
{
if (s[i] == '(' || s[i] == '[' || s[i] == '{')
{
st.push(s[i]);
}
else if (s[i] == ')')
{
if (!st.empty() && st.top() == '(' )
{
st.pop();
}
else
{
return false;
}
}
else if (s[i] == '}')
{
if (!st.empty() && st.top() == '{')
{
st.pop();
}
else
{
return false;
}
}
else if (s[i] == ']')
{
if ( !st.empty() && st.top() == '[' )
{
st.pop();
}
else
{
return false;
}
}
}
if (st.empty())
return true;
else
return false;
}
};
xxxxxxxxxx
#include<iostream>
#include<stack>
using namespace std;
bool isValid(string s) {
stack<char> st;
for (int i = 0; i < s.length(); i++)
{
if (s[i] == '(' || s[i] == '{' || s[i] == '[')
st.push(s[i]);
if (!st.empty())
{
if (s[i] == ')')
{
if (st.top() == '(')
{
st.pop();
continue;
}
else
break;
}
//
if (s[i] == '}')
{
if (st.top() == '{')
{
st.pop();
continue;
}
else
break;
}
//
if (s[i] == ']')
{
if (st.top() == '[')
{
st.pop();
continue;
}
else
break;
}
}
else
return false;
}
return st.empty() ? true : false;
}
int main()
{
string s;
cin >> s;
cout << isValid(s) << "\n";
return 0;
}
xxxxxxxxxx
HashMap<Character, Character> map = new HashMap<Character, Character>();
map.put('(', ')');
map.put('[', ']');
map.put('{', '}');
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char curr = s.charAt(i);
if (map.keySet().contains(curr)) {
stack.push(curr);
} else if (map.values().contains(curr)) {
if (!stack.empty() && map.get(stack.peek()) == curr) {
stack.pop();
} else {
return false;
}
}
}
return stack.empty();