diff options
| author | crupest <crupest@outlook.com> | 2020-08-17 20:49:29 +0800 | 
|---|---|---|
| committer | crupest <crupest@outlook.com> | 2020-08-17 20:49:29 +0800 | 
| commit | a2ef39abaf763d81fc7cee30a938949d13882897 (patch) | |
| tree | 156ed4c6d9ab7b2b0f2b1c0fcc99f4990b002288 /works/solutions/cpp | |
| parent | de3af9e609783938250466943fd093d9b2d7f879 (diff) | |
| download | crupest-a2ef39abaf763d81fc7cee30a938949d13882897.tar.gz crupest-a2ef39abaf763d81fc7cee30a938949d13882897.tar.bz2 crupest-a2ef39abaf763d81fc7cee30a938949d13882897.zip  | |
import(solutions): Add problem 20 .
Diffstat (limited to 'works/solutions/cpp')
| -rw-r--r-- | works/solutions/cpp/20.cpp | 55 | 
1 files changed, 55 insertions, 0 deletions
diff --git a/works/solutions/cpp/20.cpp b/works/solutions/cpp/20.cpp new file mode 100644 index 0000000..e994e96 --- /dev/null +++ b/works/solutions/cpp/20.cpp @@ -0,0 +1,55 @@ +#include <string>
 +
 +using std::string;
 +
 +#include <stack>
 +
 +class Solution
 +{
 +public:
 +    inline static char get_companion(char c)
 +    {
 +        switch (c)
 +        {
 +        case ')':
 +            return '(';
 +        case ']':
 +            return '[';
 +        default:
 +            return '{';
 +        }
 +    }
 +
 +    bool isValid(string s)
 +    {
 +        std::stack<char> stack;
 +
 +        for (const auto c : s)
 +        {
 +            switch (c)
 +            {
 +            case '(':
 +            case '[':
 +            case '{':
 +            {
 +                stack.push(c);
 +                break;
 +            }
 +            case ')':
 +            case ']':
 +            default:
 +            {
 +                if (stack.empty())
 +                    return false;
 +                const auto top = stack.top();
 +                const char companion = get_companion(c);
 +                if (top != companion)
 +                    return false;
 +                stack.pop();
 +            }
 +            }
 +        }
 +
 +        return stack.empty();
 +    }
 +};
  | 
