-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidParentheses.cpp
More file actions
48 lines (45 loc) · 1.05 KB
/
validParentheses.cpp
File metadata and controls
48 lines (45 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <string>
#include <vector>
// https://leetcode.com/problems/valid-parentheses/
class Solution
{
public:
bool isValid(std::string s)
{
int length = s.size();
if (length == 1)
return false;
std::vector<std::string> openedStack;
bool result = true;
for (int i = 0; i < length && result; i += 1)
{
char curChar = s[i];
std::string curStr;
curStr.push_back(curChar);
if (
curStr == "{" || curStr == "[" || curStr == "(")
{
openedStack.push_back(curStr);
}
else if (openedStack.size() > 0)
{
std::string curOpenedStr = openedStack.back();
openedStack.pop_back();
if (curStr == "}" && curOpenedStr != "{")
result = false;
if (curStr == "]" && curOpenedStr != "[")
result = false;
if (curStr == ")" && curOpenedStr != "(")
result = false;
}
else
{
return false;
}
}
if (result == false)
return false;
return openedStack.empty();
}
};