1 题目简述
Given a string containing justthe characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
给定一个包含只字符'('
, ')'
, '{'
, '}'
, '['
和 ']'
的字符串,确定输入字符串是否有效。
The brackets must close in thecorrect order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.
括号必须以正确的顺序关闭, "()"
和 "()[]{}"
是有效的,但"(]"
和 "([)]"
是无效的。
2 答案详解
(1) 解决思想
本次解答采用C++编写,C++相对于C语言的一个重要的特点是:面向对象编程(OOP),故我们采用类的方法来实现所述要求。
我们知道输入的字符串三种类型的括弧只有在少数几种情况下有效,其他情况均为无效,即字符'
('
的下一个字符为')'
, '{'
的下一个字符为'}'
, '['
的下一个字符为 ']'
,且不存在落单的括弧时,该字符串有效。字符串无效的情况有很多,包括:存在除括弧的别的字符,字符串为空,存在未配对的括弧等。
对于配对的括弧,可以采用栈stack来解决。遍历字符串,当遇见'('
, '{'
, '['
其中之一时入栈,先判断栈是否为空,不为空则返回false,为空则将其入栈;之后遇见配对的括弧后出栈;若遇见别的字符且栈为空,则直接范围false;最后遍历完字符串后,若栈为空则返回true,不为空则返回false。
(2) 设计程序
所设计的程序采用类模板,程序如下:
#include <iostream>
#include <string>
#include <stack>
using std::cout;
using std::endl;
using std::string;
using std::stack;
using std::boolalpha;
using std::noboolalpha;
template<class T>
class Solution
{
private:
T str_;
public:
Solution(const T& str):str_(str) {}
bool isValid();
};
template<class T>
bool Solution<T>::isValid()
{
if(str_.size() == 0) {
return false;
}
stack<char> st;
for(int i = 0; i < str_.size(); i++) {
if( st.empty() and (str_[i]=='{' or str_[i]=='[' or str_[i]=='(') ) {
st.push(str_[i]);
} else if( str_[i]=='}' and st.top()=='{') {
st.pop();
} else if( str_[i]==']' and st.top()=='[') {
st.pop();
} else if( str_[i]==')' and st.top()=='(') {
st.pop();
} else {
return false;
}
}
return st.empty();
}
int main()
{
string str="[](}){}";
cout << "The string is:" << str << endl;
Solution<string> sol(str);
cout << "It is Valid? ------";
cout << boolalpha << sol.isValid() << noboolalpha << endl;
}
程序运行结果为:
The string is:[](}){}
It is Valid? ------false