Length of the longest balanced parentheses in a string

Here given code implementation process.

import java.util.Stack;
/*
    Java program for
    Length of the longest balanced parentheses in a string
*/
public class BalancedParentheses
{
	public void lengthLongestBParentheses(String expression)
	{
		int length = 0;
		// Get the length of expression which is contains 
		// open and close parentheses.
		int n = expression.length();
		if (n > 0)
		{
			Stack < Integer > record = new Stack < Integer > ();
			int count = -1;
			record.push(-1);
			for (int i = 0; i < n; ++i)
			{
				if (expression.charAt(i) == ')')
				{
					// Remove top element
					record.pop();
					if (record.isEmpty() == false)
					{
						// When record not empty
						count = i - record.peek();
						if (count > length)
						{
							length = count;
						}
					}
					else
					{
						// When stack empty then insert current location
						record.push(i);
					}
				}
				else if (expression.charAt(i) == '(')
				{
					// Add current location
					record.push(i);
				}
				else
				{
					// Invalid expression 
					return;
				}
			}
		}
		// Display given expression
		System.out.println(" Given expression : " + expression);
		// Display calculated result
		System.out.println(" Length : " + length);
	}
	public static void main(String[] args)
	{
		BalancedParentheses task = new BalancedParentheses();
		// "()))()())"
		//      ----
		// Ans 4
		task.lengthLongestBParentheses("()))()())");
		// ")()))((()))((()("
		//       ------
		// Ans 6
		task.lengthLongestBParentheses(")()))((()))((()(");
		// ")))((("
		// Ans 0
		task.lengthLongestBParentheses(")))(((");
	}
}

Output

 Given expression : ()))()())
 Length : 4
 Given expression : )()))((()))((()(
 Length : 6
 Given expression : )))(((
 Length : 0
// Include header file
#include <iostream>
#include <stack>
#include <string>

using namespace std;
/*
    C++ program for
    Length of the longest balanced parentheses in a string
*/
class BalancedParentheses
{
	public: void lengthLongestBParentheses(string expression)
	{
		int length = 0;
		// Get the length of expression which is contains 
		// open and close parentheses.
		int n = expression.length();
		if (n > 0)
		{
			stack < int > record;
			int count = -1;
			record.push(-1);
			for (int i = 0; i < n; ++i)
			{
				if (expression[i] == ')')
				{
					// Remove top element
					record.pop();
					if (record.empty() == false)
					{
						// When record not empty
						count = i - record.top();
						if (count > length)
						{
							length = count;
						}
					}
					else
					{
						// When stack empty then insert current location
						record.push(i);
					}
				}
				else if (expression[i] == '(')
				{
					// Add current location
					record.push(i);
				}
				else
				{
					// Invalid expression 
					return;
				}
			}
		}
		// Display given expression
		cout << " Given expression : " << expression << endl;
		// Display calculated result
		cout << " Length : " << length << endl;
	}
};
int main()
{
	BalancedParentheses *task = new BalancedParentheses();
	// "()))()())"
	//      ----
	// Ans 4
	task->lengthLongestBParentheses("()))()())");
	// ")()))((()))((()("
	//       ------
	// Ans 6
	task->lengthLongestBParentheses(")()))((()))((()(");
	// ")))((("
	// Ans 0
	task->lengthLongestBParentheses(")))(((");
	return 0;
}

Output

 Given expression : ()))()())
 Length : 4
 Given expression : )()))((()))((()(
 Length : 6
 Given expression : )))(((
 Length : 0
// Include namespace system
using System;
using System.Collections.Generic;
/*
    Csharp program for
    Length of the longest balanced parentheses in a string
*/
public class BalancedParentheses
{
	public void lengthLongestBParentheses(String expression)
	{
		int length = 0;
		// Get the length of expression which is contains 
		// open and close parentheses.
		int n = expression.Length;
		if (n > 0)
		{
			Stack < int > record = new Stack < int > ();
			int count = -1;
			record.Push(-1);
			for (int i = 0; i < n; ++i)
			{
				if (expression[i] == ')')
				{
					// Remove top element
					record.Pop();
					if ((record.Count == 0) == false)
					{
						// When record not empty
						count = i - record.Peek();
						if (count > length)
						{
							length = count;
						}
					}
					else
					{
						// When stack empty then insert current location
						record.Push(i);
					}
				}
				else if (expression[i] == '(')
				{
					// Add current location
					record.Push(i);
				}
				else
				{
					// Invalid expression 
					return;
				}
			}
		}
		// Display given expression
		Console.WriteLine(" Given expression : " + expression);
		// Display calculated result
		Console.WriteLine(" Length : " + length);
	}
	public static void Main(String[] args)
	{
		BalancedParentheses task = new BalancedParentheses();
		// "()))()())"
		//      ----
		// Ans 4
		task.lengthLongestBParentheses("()))()())");
		// ")()))((()))((()("
		//       ------
		// Ans 6
		task.lengthLongestBParentheses(")()))((()))((()(");
		// ")))((("
		// Ans 0
		task.lengthLongestBParentheses(")))(((");
	}
}

Output

 Given expression : ()))()())
 Length : 4
 Given expression : )()))((()))((()(
 Length : 6
 Given expression : )))(((
 Length : 0
package main
import "fmt"
/*
    Go program for
    Length of the longest balanced parentheses in a string
*/

func lengthLongestBParentheses(expression string) {
	var length int = 0
	// Get the length of expression which is contains 
	// open and close parentheses.
	var n int = len(expression)
	if n > 0 {
		var record = make([]int,0);
		var count int = -1
		record = append(record, -1)
		for i := 0 ; i < n ; i++ {
			if expression[i] == ')' {
				// Remove top element
				record = record[: len(record) - 1]
				if len(record) > 0 {
					// When record not empty
					count = i - record[len(record) - 1]
					if count > length {
						length = count
					}
				} else {
					// When stack empty then insert current location
					record = append(record, i)
				}
			} else if expression[i] == '(' {
				// Add current location
				record = append(record, i)
			} else {
				// Invalid expression 
				return
			}
		}
	}
	// Display given expression
	fmt.Println(" Given expression : ", expression)
	// Display calculated result
	fmt.Println(" Length : ", length)
}
func main() {
	
	// "()))()())"
	//      ----
	// Ans 4
	lengthLongestBParentheses("()))()())")
	// ")()))((()))((()("
	//       ------
	// Ans 6
	lengthLongestBParentheses(")()))((()))((()(")
	// ")))((("
	// Ans 0
	lengthLongestBParentheses(")))(((")
}

Output

 Given expression :  ()))()())
 Length :  4
 Given expression :  )()))((()))((()(
 Length :  6
 Given expression :  )))(((
 Length :  0
<?php
/*
    Php program for
    Length of the longest balanced parentheses in a string
*/
class BalancedParentheses
{
	public	function lengthLongestBParentheses($expression)
	{
		$length = 0;
		// Get the length of expression which is contains 
		// open and close parentheses.
		$n = strlen($expression);
		if ($n > 0)
		{
			$record = array();
			$count = -1;
			array_push($record, -1);
			for ($i = 0; $i < $n; ++$i)
			{
				if ($expression[$i] == ')')
				{
					// Remove top element
					array_pop($record);
					if (empty($record) == false)
					{
						// When record not empty
						$count = $i - end($record);
						if ($count > $length)
						{
							$length = $count;
						}
					}
					else
					{
						// When stack empty then insert current location
						array_push($record, $i);
					}
				}
				else if ($expression[$i] == '(')
				{
					// Add current location
					array_push($record, $i);
				}
				else
				{
					// Invalid expression 
					return;
				}
			}
		}
		// Display given expression
		echo(" Given expression : ".$expression."\n");
		// Display calculated result
		echo(" Length : ".$length."\n");
	}
}

function main()
{
	$task = new BalancedParentheses();
	// "()))()())"
	//      ----
	// Ans 4
	$task->lengthLongestBParentheses("()))()())");
	// ")()))((()))((()("
	//       ------
	// Ans 6
	$task->lengthLongestBParentheses(")()))((()))((()(");
	// ")))((("
	// Ans 0
	$task->lengthLongestBParentheses(")))(((");
}
main();

Output

 Given expression : ()))()())
 Length : 4
 Given expression : )()))((()))((()(
 Length : 6
 Given expression : )))(((
 Length : 0
/*
    Node JS program for
    Length of the longest balanced parentheses in a string
*/
class BalancedParentheses
{
	lengthLongestBParentheses(expression)
	{
		var length = 0;
		// Get the length of expression which is contains 
		// open and close parentheses.
		var n = expression.length;
		if (n > 0)
		{
			var record = [];
			var count = -1;
			record.push(-1);
			for (var i = 0; i < n; ++i)
			{
				if (expression.charAt(i) == ')')
				{
					// Remove top element
					record.pop();
					if ((record.length == 0) == false)
					{
						// When record not empty
						count = i - record[record.length - 1];
						if (count > length)
						{
							length = count;
						}
					}
					else
					{
						// When stack empty then insert current location
						record.push(i);
					}
				}
				else if (expression.charAt(i) == '(')
				{
					// Add current location
					record.push(i);
				}
				else
				{
					// Invalid expression 
					return;
				}
			}
		}
		// Display given expression
		console.log(" Given expression : " + expression);
		// Display calculated result
		console.log(" Length : " + length);
	}
}

function main()
{
	var task = new BalancedParentheses();
	// "()))()())"
	//      ----
	// Ans 4
	task.lengthLongestBParentheses("()))()())");
	// ")()))((()))((()("
	//       ------
	// Ans 6
	task.lengthLongestBParentheses(")()))((()))((()(");
	// ")))((("
	// Ans 0
	task.lengthLongestBParentheses(")))(((");
}
main();

Output

 Given expression : ()))()())
 Length : 4
 Given expression : )()))((()))((()(
 Length : 6
 Given expression : )))(((
 Length : 0
#    Python 3 program for
#    Length of the longest balanced parentheses in a string
class BalancedParentheses :
	def lengthLongestBParentheses(self, expression) :
		length = 0
		#  Get the length of expression which is contains 
		#  open and close parentheses.
		n = len(expression)
		if (n > 0) :
			record = []
			count = -1
			record.append(-1)
			i = 0
			while (i < n) :
				if (expression[i] == ')') :
					#  Remove top element
					record.pop()
					if ((len(record) == 0) == False) :
						#  When record not empty
						count = i - record[-1]
						if (count > length) :
							length = count
						
					else :
						#  When stack empty then insert current location
						record.append(i)
					
				elif (expression[i] == '(') :
					#  Add current location
					record.append(i)
				else :
					#  Invalid expression 
					return
				
				i += 1
			
		
		#  Display given expression
		print(" Given expression : ", expression)
		#  Display calculated result
		print(" Length : ", length)
	

def main() :
	task = BalancedParentheses()
	#  "()))()())"
	#       ----
	#  Ans 4
	task.lengthLongestBParentheses("()))()())")
	#  ")()))((()))((()("
	#        ------
	#  Ans 6
	task.lengthLongestBParentheses(")()))((()))((()(")
	#  ")))((("
	#  Ans 0
	task.lengthLongestBParentheses(")))(((")

if __name__ == "__main__": main()

Output

 Given expression :  ()))()())
 Length :  4
 Given expression :  )()))((()))((()(
 Length :  6
 Given expression :  )))(((
 Length :  0
#    Ruby program for
#    Length of the longest balanced parentheses in a string
class BalancedParentheses 
	def lengthLongestBParentheses(expression) 
		length = 0
		#  Get the length of expression which is contains 
		#  open and close parentheses.
		n = expression.length
		if (n > 0) 
			record = []
			count = -1
			record.push(-1)
			i = 0
			while (i < n) 
				if (expression[i] == ')') 
					#  Remove top element
					record.pop()
					if ((record.length == 0) == false) 
						#  When record not empty
						count = i - record.last
						if (count > length) 
							length = count
						end

					else
 
						#  When stack empty then insert current location
						record.push(i)
					end

				elsif (expression[i] == '(') 
					#  Add current location
					record.push(i)
				else
 
					#  Invalid expression 
					return
				end

				i += 1
			end

		end

		#  Display given expression
		print(" Given expression : ", expression, "\n")
		#  Display calculated result
		print(" Length : ", length, "\n")
	end

end

def main() 
	task = BalancedParentheses.new()
	#  "()))()())"
	#       ----
	#  Ans 4
	task.lengthLongestBParentheses("()))()())")
	#  ")()))((()))((()("
	#        ------
	#  Ans 6
	task.lengthLongestBParentheses(")()))((()))((()(")
	#  ")))((("
	#  Ans 0
	task.lengthLongestBParentheses(")))(((")
end

main()

Output

 Given expression : ()))()())
 Length : 4
 Given expression : )()))((()))((()(
 Length : 6
 Given expression : )))(((
 Length : 0
import scala.collection.mutable._;
/*
    Scala program for
    Length of the longest balanced parentheses in a string
*/
class BalancedParentheses()
{
	def lengthLongestBParentheses(expression: String): Unit = {
		var length: Int = 0;
		// Get the length of expression which is contains 
		// open and close parentheses.
		var n: Int = expression.length();
		if (n > 0)
		{
			var record: Stack[Int] = new Stack[Int]();
			var count: Int = -1;
			record.push(-1);
			var i: Int = 0;
			while (i < n)
			{
				if (expression.charAt(i) == ')')
				{
					// Remove top element
					record.pop;
					if (record.isEmpty == false)
					{
						// When record not empty
						count = i - record.top;
						if (count > length)
						{
							length = count;
						}
					}
					else
					{
						// When stack empty then insert current location
						record.push(i);
					}
				}
				else if (expression.charAt(i) == '(')
				{
					// Add current location
					record.push(i);
				}
				else
				{
					// Invalid expression 
					return;
				}
				i += 1;
			}
		}
		// Display given expression
		println(" Given expression : " + expression);
		// Display calculated result
		println(" Length : " + length);
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var task: BalancedParentheses = new BalancedParentheses();
		// "()))()())"
		//      ----
		// Ans 4
		task.lengthLongestBParentheses("()))()())");
		// ")()))((()))((()("
		//       ------
		// Ans 6
		task.lengthLongestBParentheses(")()))((()))((()(");
		// ")))((("
		// Ans 0
		task.lengthLongestBParentheses(")))(((");
	}
}

Output

 Given expression : ()))()())
 Length : 4
 Given expression : )()))((()))((()(
 Length : 6
 Given expression : )))(((
 Length : 0
import Foundation;
/*
    Swift 4 program for
    Length of the longest balanced parentheses in a string
*/
struct Stack
{
	private
	var items: [Int] = []
	func peek()->Int
	{
		if (self.isEmpty()==false)
		{
			return items.first!
		}
		else
		{
			fatalError("This stack is empty.")
		}
	}
	func isEmpty()->Bool
	{
		return items.count == 0
	}
	mutating func pop()->Int
	{
		return items.removeFirst()
	}
	mutating func push(_ data: Int)
	{
		items.insert(data, at: 0)
	}
}
class BalancedParentheses
{
	func lengthLongestBParentheses(_ exp: String)
	{
      	var expression = Array(exp);
		var length: Int = 0;
		// Get the length of expression which is contains 
		// open and close parentheses.
		let n: Int = expression.count;
		if (n > 0)
		{
			var record = Stack();
			var count: Int = -1;
			record.push(-1);
			var i: Int = 0;
			while (i < n)
			{
				if (expression[i] == ")")
				{
					// Remove top element
					let _ = record.pop();
					if (record.isEmpty() == false)
					{
						// When record not empty
						count = i - record.peek();
						if (count > length)
						{
							length = count;
						}
					}
					else
					{
						// When stack empty then insert current location
						record.push(i);
					}
				}
				else if (expression[i] == "(")
				{
					// Add current location
					record.push(i);
				}
				else
				{
					// Invalid expression 
					return;
				}
				i += 1;
			}
		}
		// Display given expression
		print(" Given expression : ", exp);
		// Display calculated result
		print(" Length : ", length);
	}
}
func main()
{
	let task: BalancedParentheses = BalancedParentheses();
	// "()))()())"
	//      ----
	// Ans 4
	task.lengthLongestBParentheses("()))()())");
	// ")()))((()))((()("
	//       ------
	// Ans 6
	task.lengthLongestBParentheses(")()))((()))((()(");
	// ")))((("
	// Ans 0
	task.lengthLongestBParentheses(")))(((");
}
main();

Output

 Given expression :  ()))()())
 Length :  4
 Given expression :  )()))((()))((()(
 Length :  6
 Given expression :  )))(((
 Length :  0
import java.util.Stack;
/*
    Kotlin program for
    Length of the longest balanced parentheses in a string
*/
class BalancedParentheses
{
	fun lengthLongestBParentheses(expression: String): Unit
	{
		var length: Int = 0;
		// Get the length of expression which is contains 
		// open and close parentheses.
		val n: Int = expression.length;
		if (n > 0)
		{
			var record: Stack < Int > = Stack < Int > ();
			var count: Int = -1;
			record.push(count);
			var i: Int = 0;
			while (i < n)
			{
				if (expression.get(i) == ')')
				{
					// Remove top element
					record.pop();
					if (record.empty() == false)
					{
						// When record not empty
						count = i - record.peek();
						if (count > length)
						{
							length = count;
						}
					}
					else
					{
						// When stack empty then insert current location
						record.push(i);
					}
				}
				else if (expression.get(i) == '(')
				{
					// Add current location
					record.push(i);
				}
				else
				{
					// Invalid expression 
					return;
				}
				i += 1;
			}
		}
		// Display given expression
		println(" Given expression : " + expression);
		// Display calculated result
		println(" Length : " + length);
	}
}
fun main(args: Array < String > ): Unit
{
	val task: BalancedParentheses = BalancedParentheses();
	// "()))()())"
	//      ----
	// Ans 4
	task.lengthLongestBParentheses("()))()())");
	// ")()))((()))((()("
	//       ------
	// Ans 6
	task.lengthLongestBParentheses(")()))((()))((()(");
	// ")))((("
	// Ans 0
	task.lengthLongestBParentheses(")))(((");
}

Output

 Given expression : ()))()())
 Length : 4
 Given expression : )()))((()))((()(
 Length : 6
 Given expression : )))(((
 Length : 0


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved