-
スタックを使用する方法: この方法では、開き括弧(例: '('、'{'、'[')をスタックにプッシュし、閉じ括弧(例: ')'、'}'、']')が現れるたびにスタックから対応する開き括弧をポップします。すべての括弧が正しく対応している場合、最終的にスタックは空になるはずです。
def is_balanced(string): stack = [] open_brackets = ['(', '{', '['] close_brackets = [')', '}', ']'] for char in string: if char in open_brackets: stack.append(char) elif char in close_brackets: if not stack or open_brackets.index(stack.pop()) != close_brackets.index(char): return False return len(stack) == 0
-
再帰を使用する方法: 再帰を使用して、括弧の対応関係を再帰的にチェックすることもできます。文字列の先頭から順番に文字を調べ、開き括弧と閉じ括弧が正しく対応しているかどうかを確認します。
def is_balanced(string): open_brackets = ['(', '{', '['] close_brackets = [')', '}', ']'] def check_balance(string, index, stack): if index == len(string): return len(stack) == 0 if string[index] in open_brackets: stack.append(string[index]) elif string[index] in close_brackets: if not stack or open_brackets.index(stack.pop()) != close_brackets.index(string[index]): return False return check_balance(string, index + 1, stack) return check_balance(string, 0, [])
-
正規表現を使用する方法: 正規表現を使って括弧の対応を検出することもできます。以下の正規表現パターンは、バランスの取れた括弧を検出するために使用できます。
import re def is_balanced(string): pattern = r'\([^()]*\)|\{[^{}]*\}|\[[^\[\]]*\]' while re.search(pattern, string): string = re.sub(pattern, '', string) return len(string) == 0
これらはいくつかの一般的な方法ですが、他にも様々なアルゴリズムやアプローチが存在します。選択した方法は、使用する言語や具体的な要件によって異なる場合があります。括弧のバランスを検出するための最適な方法を選択するために、特定の要件や制約を考慮することをお勧めします。
Title: Detecting and Analyzing Balanced Braces - Methods with Code Examples
Tags: Balanced Braces, String Processing, Stack, Recursion, Regular Expressions, Algorithms
Content: Detecting balanced braces (brackets) is a very common task in string processing. In this blog post, I will introduce several methods to check whether braces are balanced or not, along with code examples. Below, I will provide some approaches and code examples for your reference.
-
Using a stack: This method involves pushing opening braces (e.g., '(', '{', '[') onto a stack and popping the corresponding opening brace from the stack whenever a closing brace (e.g., ')', '}', ']') appears. If all braces are properly matched, the stack should be empty in the end.
def is_balanced(string): stack = [] open_braces = ['(', '{', '['] close_braces = [')', '}', ']'] for char in string: if char in open_braces: stack.append(char) elif char in close_braces: if not stack or open_braces.index(stack.pop()) != close_braces.index(char): return False return len(stack) == 0
-
Using recursion: It is also possible to check the matching of braces recursively. Starting from the beginning of the string, examine each character and verify whether the opening and closing braces are properly matched.
def is_balanced(string): open_braces = ['(', '{', '['] close_braces = [')', '}', ']'] def check_balance(string, index, stack): if index == len(string): return len(stack) == 0 if string[index] in open_braces: stack.append(string[index]) elif string[index] in close_braces: if not stack or open_braces.index(stack.pop()) != close_braces.index(string[index]): return False return check_balance(string, index + 1, stack) return check_balance(string, 0, [])
-
Using regular expressions: Regular expressions can also be used to detect the matching of braces. The following regular expression pattern can be used to detect balanced braces:
import re def is_balanced(string): pattern = r'\([^()]*\)|\{[^{}]*\}|\[[^\[\]]*\]' while re.search(pattern, string): string = re.sub(pattern, '', string) return len(string) == 0
These are some common methods, but there are various other algorithms and approaches available as well. The choice of method may vary depending on the language used and specific requirements. It is recommended to consider specific requirements and constraints to select the optimal method for detecting balanced braces.
The title and tags for this blog post are "Detecting and Analyzing Balanced Braces - Methods with Code Examples" and "Balanced Braces, String Processing, Stack, Recursion, Regular Expressions, Algorithms" respectively.