LeetCode 20. Valid Parentheses
1970 ワード
質問する
👉 20. Valid Parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
解答方法
「」と入力した場合、カッコは完了しません.
コード#コード# class Solution {
public:
bool isValid(string s) {
stack<char> list;
bool result = false;
for (int i = 0; i < s.size(); i++) {
char c = s[i];
if (c == '(' || c == '{' || c == '[') {
list.push(c);
}
if (list.empty()) {
return false;
}else if (c == ')' || c == '}' || c == ']') {
char peek = list.top();
cout << c <<", " << peek << endl;
if (c == ')' && peek == '(') {
list.pop();
} else if (c == '}' && peek == '{') {
list.pop();
} else if (c == ']' && peek == '[') {
list.pop();
} else {
return false;
}
}
}
return list.empty();
}
};
Reference
この問題について(LeetCode 20. Valid Parentheses), 我々は、より多くの情報をここで見つけました
https://velog.io/@garin0112/LeetCode-20.-Valid-Parentheses
テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol
class Solution {
public:
bool isValid(string s) {
stack<char> list;
bool result = false;
for (int i = 0; i < s.size(); i++) {
char c = s[i];
if (c == '(' || c == '{' || c == '[') {
list.push(c);
}
if (list.empty()) {
return false;
}else if (c == ')' || c == '}' || c == ']') {
char peek = list.top();
cout << c <<", " << peek << endl;
if (c == ')' && peek == '(') {
list.pop();
} else if (c == '}' && peek == '{') {
list.pop();
} else if (c == ']' && peek == '[') {
list.pop();
} else {
return false;
}
}
}
return list.empty();
}
};
Reference
この問題について(LeetCode 20. Valid Parentheses), 我々は、より多くの情報をここで見つけました https://velog.io/@garin0112/LeetCode-20.-Valid-Parenthesesテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol