1. 程式人生 > >20. Valid Parentheses題目和答案詳解

20. Valid Parentheses題目和答案詳解

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