LeetCode--Valid Parentheses
Question
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
这个题目的思想就是利用堆实现一个函数:int find_match();
- 当函数返回值为-1的时候,表明在堆中没有找到匹配的括号,那么需要将新的括号压入堆中;
- 当函数返回值为0的时候,表明在堆的最顶端找到了匹配的括号,那么需要将堆中的括号弹出;
- 当函数返回值为1的时候,表明在堆的其他位置找到了匹配的括号,那么括号匹配失败退出;
作者用map实现了括号的映射,便于计算是否匹配;用vector模拟stack,因为vector比较熟悉吧。
具体实现
#include <iostream>
#include <map>
#include <vector>
using namespace std;
class Solution {
public:
bool isValid(string s) {
init();
for (int i = 0; i < s.length(); i++) {
int value = bracket2int.find(s[i])->second;
int res = find_match(value);
if (res == -1)
brackets.push_back(value);
else if (res == 0)
brackets.pop_back();
else
return false;
}
if (brackets.size() != 0)
return false;
else
return true;
}
int find_match(int input) {
int index = -1;
for (int i = brackets.size() - 1; i >= 0; i--) {
if (brackets[i] + input == 0) {
index = i;
break;
}
}
// 堆最顶端匹配
if (brackets.size() != 0 && index == brackets.size() - 1)
return 0;
//没有找到匹配
else if (index == -1)
return -1;
//其他位置找到匹配
else
return 1;
}
void init() {
bracket2int.insert(map<char, int>::value_type('(', 1));
bracket2int.insert(map<char, int>::value_type(')', -1));
bracket2int.insert(map<char, int>::value_type('[', 2));
bracket2int.insert(map<char, int>::value_type(']', -2));
bracket2int.insert(map<char, int>::value_type('{', 3));
bracket2int.insert(map<char, int>::value_type('}', -3));
}
private:
map<char, int> bracket2int;
vector<int> brackets;
};
int main() {
Solution* solution = new Solution();
string str = "";
if (solution->isValid(str))
cout << "True" << endl;
else
cout << "False" << endl;
return 0;
}