Leetcode戦闘:20.効果的なかっこ

トピック:

のみ与えられた'('、 ')'の文字列を含む、 '{'、 '}'、 '['、 ']'、文字列が有効であるかどうかを決定します。
有効な文字列を満たしている必要があります。

  1. 左ブラケットは、同じタイプの閉じ括弧で閉じなければなりません。
  2. 左括弧が正しい順序で閉じなければなりません。

空の文字列が有効な文字列と考えることができます。

例1

输入: "()"
输出: true

例2

输入: "()[]{}"
输出: true

例3

输入: "(]"
输出: false

例4

输入: "([)]"
输出: false

例5

输入: "{[]}"
输出: true

アルゴリズム

class Solution {
public:
    bool isValid(string s) {
        int historyS[10000];
        int temp;
        int j = 0;
        unordered_map<char, int> Symbol{ {'{', 1}, { '}', -1}, {'[', 100}, {']', -100}, {'(', 1000}, {')', -1000} };
        if (Symbol[s[0]] < 0 )
            return 0;
        if (s.length() == 0)
            return 1;
        else
            historyS[0] = Symbol[s[0]];
        for (int i = 1; i < s.length(); i++) {
            int temp = Symbol[s[i]];
            if (temp < 0) {
                if (j <= -1 || temp + historyS[j] != 0 )
                    return 0;
                j--;
            }
            else {
                historyS[j + 1] = temp;
                j++;
            }
        }
        return j == -1 ? 1 : 0;
    }
};

結果:

最初の百二重

ここに画像を挿入説明

公開された129元の記事 ウォン称賛34 ビュー8028

おすすめ

転載: blog.csdn.net/qq_44315987/article/details/104883694