This article explains how to use Java to find the length of the longest balanced parentheses prefix . First, we will understand the problem using several examples and then learn two different approaches to seek it.
Problem explanation"("")", then we call it balanced. prefixes define a balanced set from the beginning of a string. For example, for the set of parentheses '(())()', only '(())' is considered.
Input and output scenarios
If the input string is
Using stack data structures
' from the stack, push it onto the stack. If you find a closing parentheses, pop the stack and increment the counter variable by 2 (the balance The length of the pair you got is 2.) Continue doing this and return a counter variable when it becomes an empty stack. Algorithm
<code><p><b>ステップ1:</b>スタックとカウンタを初期化します。</p> <p><b>ステップ2:</b>文字列の各文字を反復処理します。</p></code>
Return the counter at the end. Output
Example
<code><p><b>ステップ1:</b>スタックとカウンタを初期化します。</p>
<p><b>ステップ2:</b>文字列の各文字を反復処理します。</p></code>
" from the string, increment count by 1; if the character is ")", decrement count by 1 and increment length by 2 . Check if count is 0, if it is 0, exit the loop and return length. Example
import java.util.Stack; public class Example { public static int longestBalancedPrefix(String s) { Stack<Character> stack = new Stack<>(); int count = 0; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '(') { stack.push(c); } else if (c == ')') { if (!stack.isEmpty()) { stack.pop(); count += 2; } } if (stack.isEmpty()) { break; } } return count; } public static void main(String[] args) { String s = "((())((("; int length = longestBalancedPrefix(s); System.out.println("入力文字列は:" + s); System.out.println("最長のバランスの取れた括弧のプレフィックスの長さは:" + length); } }
The input string is ((())())(())) The longest balanced parentheses prefix length is 8
The above is the detailed content of Length of longest balanced parentheses prefix using Java. For more information, please follow other related articles on the PHP Chinese website!