Check redundant parentheses in an expression

Here given code implementation process.

import java.util.Stack;
/*
    Java program for
    Check redundant parentheses in an expression
*/
public class Redundant
{
    public void isRedundantParentheses(String exp)
    {
        // Assume given expres  
        int n = exp.length();
        // Create an empty record 
        Stack < Character > record = new Stack < Character > ();
        // Result indicator
        boolean result = false;

        // Execute loop through by size of n and until result is No
        for (int i = 0; i < n && result == false; ++i)
        {
            if (exp.charAt(i) == ')')
            {
                if (record.isEmpty())
                {
                    // Expression are not valid
                    return;
                }
                else if (record.peek() == '(')
                {
                    result = true;
                }
                else
                {

                    while (record.isEmpty() == false && record.peek() != '(')
                    {
                        // Remove element until not get open parentheses
                        record.pop();
                    }
                    if (record.isEmpty())
                    {
                        // Expression are not valid
                        return;
                    }
                    record.pop();
                }
            }
            else
            {
                record.push(exp.charAt(i));
            }
        }
        // Display given expression
        System.out.print("\n Expression : " + exp);

        if (result == true)
        {
            System.out.print("\n Redundant parentheses exists");
        }
        else
        {
            System.out.print("\n Redundant parentheses not exists");
        }
    }
    public static void main(String[] args)
    {
        Redundant task = new Redundant();
        // Test 
        task.isRedundantParentheses("(a+b-(c + ((a+b))))");
        task.isRedundantParentheses("((a+b) -(b-(c*d)))");
        task.isRedundantParentheses("((a+b) + (c+a))");
        task.isRedundantParentheses("(a+b) + ((c))");
    }
}

Output

 Expression : (a+b-(c + ((a+b))))
 Redundant parentheses exists
 Expression : ((a+b) -(b-(c*d)))
 Redundant parentheses not exists
 Expression : ((a+b) + (c+a))
 Redundant parentheses not exists
 Expression : (a+b) + ((c))
 Redundant parentheses exists
// Include header file
#include <iostream>
#include <stack>
#include <string>

using namespace std;
/*
    C++ program for
    Check redundant parentheses in an expression
*/
class Redundant
{
	public: void isRedundantParentheses(string exp)
	{
		// Assume given expres  
		int n = exp.length();
		// Create an empty record 
		stack < char > record;
		// Result indicator
		bool result = false;
		// Execute loop through by size of n and until result is No
		for (int i = 0; i < n && result == false; ++i)
		{
			if (exp[i] == ')')
			{
				if (record.empty())
				{
					// Expression are not valid
					return;
				}
				else if (record.top() == '(')
				{
					result = true;
				}
				else
				{
					while (record.empty() == false && record.top() != '(')
					{
						// Remove element until not get open parentheses
						record.pop();
					}
					if (record.empty())
					{
						// Expression are not valid
						return;
					}
					record.pop();
				}
			}
			else
			{
				record.push(exp[i]);
			}
		}
		// Display given expression
		cout << "\n Expression : " << exp;
		if (result == true)
		{
			cout << "\n Redundant parentheses exists";
		}
		else
		{
			cout << "\n Redundant parentheses not exists";
		}
	}
};
int main()
{
	Redundant *task = new Redundant();
	// Test 
	task->isRedundantParentheses("(a+b-(c + ((a+b))))");
	task->isRedundantParentheses("((a+b) -(b-(c*d)))");
	task->isRedundantParentheses("((a+b) + (c+a))");
	task->isRedundantParentheses("(a+b) + ((c))");
	return 0;
}

Output

 Expression : (a+b-(c + ((a+b))))
 Redundant parentheses exists
 Expression : ((a+b) -(b-(c*d)))
 Redundant parentheses not exists
 Expression : ((a+b) + (c+a))
 Redundant parentheses not exists
 Expression : (a+b) + ((c))
 Redundant parentheses exists
// Include namespace system
using System;
using System.Collections.Generic;
/*
    Csharp program for
    Check redundant parentheses in an expression
*/
public class Redundant
{
	public void isRedundantParentheses(String exp)
	{
		// Assume given expres  
		int n = exp.Length;
		// Create an empty record 
		Stack < char > record = new Stack < char > ();
		// Result indicator
		Boolean result = false;
		// Execute loop through by size of n and until result is No
		for (int i = 0; i < n && result == false; ++i)
		{
			if (exp[i] == ')')
			{
				if ((record.Count == 0))
				{
					// Expression are not valid
					return;
				}
				else if (record.Peek() == '(')
				{
					result = true;
				}
				else
				{
					while ((record.Count != 0)  && record.Peek() != '(')
					{
						// Remove element until not get open parentheses
						record.Pop();
					}
					if ((record.Count == 0))
					{
						// Expression are not valid
						return;
					}
					record.Pop();
				}
			}
			else
			{
				record.Push(exp[i]);
			}
		}
		// Display given expression
		Console.Write("\n Expression : " + exp);
		if (result == true)
		{
			Console.Write("\n Redundant parentheses exists");
		}
		else
		{
			Console.Write("\n Redundant parentheses not exists");
		}
	}
	public static void Main(String[] args)
	{
		Redundant task = new Redundant();
		// Test 
		task.isRedundantParentheses("(a+b-(c + ((a+b))))");
		task.isRedundantParentheses("((a+b) -(b-(c*d)))");
		task.isRedundantParentheses("((a+b) + (c+a))");
		task.isRedundantParentheses("(a+b) + ((c))");
	}
}

Output

 Expression : (a+b-(c + ((a+b))))
 Redundant parentheses exists
 Expression : ((a+b) -(b-(c*d)))
 Redundant parentheses not exists
 Expression : ((a+b) + (c+a))
 Redundant parentheses not exists
 Expression : (a+b) + ((c))
 Redundant parentheses exists
package main

import "fmt"
/*
    Go program for
    Check redundant parentheses in an expression
*/

func isRedundantParentheses(exp string) {
	// Assume given expres  
	var n int = len(exp)
	// Create an empty record 
	var record = make([]byte,0)
	// Result indicator
	var result bool = false
	// Execute loop through by size of n and until result is No
	for i := 0 ; i < n && result == false ; i++ {
		if exp[i] == ')' {
			if len(record) == 0 {
				// Expression are not valid
				return
			} else if record[len(record) - 1] == '(' {
				result = true
			} else {
				for (len(record) > 0 && record[len(record) - 1] != '(') {
					// Remove element until not get open parentheses
					record = record[: len(record) - 1]
				}
				if len(record) == 0 {
					// Expression are not valid
					return
				}
				record = record[: len(record) - 1]
			}
		} else {
			record = append(record, exp[i])
		}
	}
	// Display given expression
	fmt.Print("\n Expression : ", exp)
	if result == true {
		fmt.Print("\n Redundant parentheses exists")
	} else {
		fmt.Print("\n Redundant parentheses not exists")
	}
}
func main() {
	
	// Test 
	isRedundantParentheses("(a+b-(c + ((a+b))))")
	isRedundantParentheses("((a+b) -(b-(c*d)))")
	isRedundantParentheses("((a+b) + (c+a))")
	isRedundantParentheses("(a+b) + ((c))")
}

Output

 Expression : (a+b-(c + ((a+b))))
 Redundant parentheses exists
 Expression : ((a+b) -(b-(c*d)))
 Redundant parentheses not exists
 Expression : ((a+b) + (c+a))
 Redundant parentheses not exists
 Expression : (a+b) + ((c))
 Redundant parentheses exists
<?php
/*
    Php program for
    Check redundant parentheses in an expression
*/
class Redundant
{
	public
	function isRedundantParentheses($exp)
	{
		// Assume given expres  
		$n = strlen($exp);
		// Create an empty record 
		$record = array();
		// Result indicator
		$result = false;
		// Execute loop through by size of n and until result is No
		for ($i = 0; $i < $n && $result == false; ++$i)
		{
			if ($exp[$i] == ')')
			{
				if (empty($record))
				{
					// Expression are not valid
					return;
				}
				else if (end($record) == '(')
				{
					$result = true;
				}
				else
				{
					while (!empty($record) && end($record) != '(')
					{
						// Remove element until not get open parentheses
						array_pop($record);
					}
					if (empty($record) == true)
					{
						// Expression are not valid
						return;
					}
					array_pop($record);
				}
			}
			else
			{
				array_push($record, $exp[$i]);
			}
		}
		// Display given expression
		echo("\n Expression : ".$exp);
		if ($result == true)
		{
			echo("\n Redundant parentheses exists");
		}
		else
		{
			echo("\n Redundant parentheses not exists");
		}
	}
}

function main()
{
	$task = new Redundant();
	// Test 
	$task->isRedundantParentheses("(a+b-(c + ((a+b))))");
	$task->isRedundantParentheses("((a+b) -(b-(c*d)))");
	$task->isRedundantParentheses("((a+b) + (c+a))");
	$task->isRedundantParentheses("(a+b) + ((c))");
}
main();

Output

 Expression : (a+b-(c + ((a+b))))
 Redundant parentheses exists
 Expression : ((a+b) -(b-(c*d)))
 Redundant parentheses not exists
 Expression : ((a+b) + (c+a))
 Redundant parentheses not exists
 Expression : (a+b) + ((c))
 Redundant parentheses exists
/*
    Node JS program for
    Check redundant parentheses in an expression
*/
class Redundant
{
	isRedundantParentheses(exp)
	{
		// Assume given expres  
		var n = exp.length;
		// Create an empty record 
		var record = [];
		// Result indicator
		var result = false;
		// Execute loop through by size of n and until result is No
		for (var i = 0; i < n && result == false; ++i)
		{
			if (exp.charAt(i) == ')')
			{
				if ((record.length == 0))
				{
					// Expression are not valid
					return;
				}
				else if (record[record.length - 1] == '(')
				{
					result = true;
				}
				else
				{
					while ((record.length == 0) == false && 
                           record[record.length - 1] != '(')
					{
						// Remove element until not get open parentheses
						record.pop();
					}
					if ((record.length == 0))
					{
						// Expression are not valid
						return;
					}
					record.pop();
				}
			}
			else
			{
				record.push(exp.charAt(i));
			}
		}
		// Display given expression
		process.stdout.write("\n Expression : " + exp);
		if (result == true)
		{
			process.stdout.write("\n Redundant parentheses exists");
		}
		else
		{
			process.stdout.write("\n Redundant parentheses not exists");
		}
	}
}

function main()
{
	var task = new Redundant();
	// Test 
	task.isRedundantParentheses("(a+b-(c + ((a+b))))");
	task.isRedundantParentheses("((a+b) -(b-(c*d)))");
	task.isRedundantParentheses("((a+b) + (c+a))");
	task.isRedundantParentheses("(a+b) + ((c))");
}
main();

Output

 Expression : (a+b-(c + ((a+b))))
 Redundant parentheses exists
 Expression : ((a+b) -(b-(c*d)))
 Redundant parentheses not exists
 Expression : ((a+b) + (c+a))
 Redundant parentheses not exists
 Expression : (a+b) + ((c))
 Redundant parentheses exists
#    Python 3 program for
#    Check redundant parentheses in an expression
class Redundant :
	def isRedundantParentheses(self, exp) :
		#  Assume given expres  
		n = len(exp)
		#  Create an empty record 
		record = []
		#  Result indicator
		result = False
		i = 0
		#  Execute loop through by size of n and until result is No
		while (i < n and result == False) :
			if (exp[i] == ')') :
				if ((len(record) == 0)) :
					#  Expression are not valid
					return
				elif (record[-1] == '(') :
					result = True
				else :
					while ((len(record) != 0) and record[-1] != '(') :
						#  Remove element until not get open parentheses
						record.pop()
					
					if ((len(record) == 0)) :
						#  Expression are not valid
						return
					
					record.pop()
				
			else :
				record.append(exp[i])
			
			i += 1
		
		#  Display given expression
		print("\n Expression : ", exp, end = "")
		if (result == True) :
			print("\n Redundant parentheses exists", end = "")
		else :
			print("\n Redundant parentheses not exists", end = "")
		
	

def main() :
	task = Redundant()
	#  Test 
	task.isRedundantParentheses("(a+b-(c + ((a+b))))")
	task.isRedundantParentheses("((a+b) -(b-(c*d)))")
	task.isRedundantParentheses("((a+b) + (c+a))")
	task.isRedundantParentheses("(a+b) + ((c))")

if __name__ == "__main__": main()

Output

 Expression :  (a+b-(c + ((a+b))))
 Redundant parentheses exists
 Expression :  ((a+b) -(b-(c*d)))
 Redundant parentheses not exists
 Expression :  ((a+b) + (c+a))
 Redundant parentheses not exists
 Expression :  (a+b) + ((c))
 Redundant parentheses exists
#    Ruby program for
#    Check redundant parentheses in an expression
class Redundant 
	def isRedundantParentheses(exp) 
		#  Assume given expres  
		n = exp.length
		#  Create an empty record 
		record = []
		#  Result indicator
		result = false
		i = 0
		#  Execute loop through by size of n and until result is No
		while (i < n && result == false) 
			if (exp[i] == ')') 
				if ((record.length == 0)) 
					#  Expression are not valid
					return
				elsif (record.last == '(') 
					result = true
				else
 
					while ((record.length != 0)  && record.last != '(') 
						#  Remove element until not get open parentheses
						record.pop()
					end

					if ((record.length == 0)) 
						#  Expression are not valid
						return
					end

					record.pop()
				end

			else
 
				record.push(exp[i])
			end

			i += 1
		end

		#  Display given expression
		print("\n Expression : ", exp)
		if (result == true) 
			print("\n Redundant parentheses exists")
		else
 
			print("\n Redundant parentheses not exists")
		end

	end

end

def main() 
	task = Redundant.new()
	#  Test 
	task.isRedundantParentheses("(a+b-(c + ((a+b))))")
	task.isRedundantParentheses("((a+b) -(b-(c*d)))")
	task.isRedundantParentheses("((a+b) + (c+a))")
	task.isRedundantParentheses("(a+b) + ((c))")
end

main()

Output

 Expression : (a+b-(c + ((a+b))))
 Redundant parentheses exists
 Expression : ((a+b) -(b-(c*d)))
 Redundant parentheses not exists
 Expression : ((a+b) + (c+a))
 Redundant parentheses not exists
 Expression : (a+b) + ((c))
 Redundant parentheses exists
import scala.collection.mutable._;
/*
    Scala program for
    Check redundant parentheses in an expression
*/
class Redundant()
{
	def isRedundantParentheses(exp: String): Unit = {
		// Assume given expres  
		var n: Int = exp.length();
		// Create an empty record 
		var record: Stack[Character] = new Stack[Character]();
		// Result indicator
		var result: Boolean = false;
		var i: Int = 0;
		// Execute loop through by size of n and until result is No
		while (i < n && result == false)
		{
			if (exp.charAt(i) == ')')
			{
				if (record.isEmpty)
				{
					// Expression are not valid
					return;
				}
				else if (record.top == '(')
				{
					result = true;
				}
				else
				{
					while (record.isEmpty == false && record.top != '(')
					{
						// Remove element until not get open parentheses
						record.pop;
					}
					if (record.isEmpty)
					{
						// Expression are not valid
						return;
					}
					record.pop;
				}
			}
			else
			{
				record.push(exp.charAt(i));
			}
			i += 1;
		}
		// Display given expression
		print("\n Expression : " + exp);
		if (result == true)
		{
			print("\n Redundant parentheses exists");
		}
		else
		{
			print("\n Redundant parentheses not exists");
		}
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var task: Redundant = new Redundant();
		// Test 
		task.isRedundantParentheses("(a+b-(c + ((a+b))))");
		task.isRedundantParentheses("((a+b) -(b-(c*d)))");
		task.isRedundantParentheses("((a+b) + (c+a))");
		task.isRedundantParentheses("(a+b) + ((c))");
	}
}

Output

 Expression : (a+b-(c + ((a+b))))
 Redundant parentheses exists
 Expression : ((a+b) -(b-(c*d)))
 Redundant parentheses not exists
 Expression : ((a+b) + (c+a))
 Redundant parentheses not exists
 Expression : (a+b) + ((c))
 Redundant parentheses exists
import Foundation;
/*
    Swift 4 program for
    Check redundant parentheses in an expression
*/
struct Stack
{
	private
	var items: [Character] = []
	func peek()->Character
	{
		if (self.isEmpty()==false)
		{
			return items.first!
		}
		else
		{
			fatalError("This stack is empty.")
		}
	}
	func isEmpty()->Bool
	{
		return items.count == 0
	}
	mutating func pop()
	{
		items.removeFirst()
	}
	mutating func push(_ data: Character)
	{
		items.insert(data, at: 0)
	}
}
class Redundant
{
	func isRedundantParentheses(_ expression: String)
	{	
      	let exp = Array(expression);
		// Assume given expres  
		let n: Int = exp.count;
		// Create an empty record 
		var record = Stack();
		// Result indicator
		var result: Bool = false;
		var i: Int = 0;
		// Execute loop through by size of n and until result is No
		while (i < n && result == false)
		{
			if (exp[i] == ")")
			{
				if (record.isEmpty())
				{
					// Expression are not valid
					return;
				}
				else if (record.peek() == "(")
				{
					result = true;
				}
				else
				{
					while (record.isEmpty() == false && (record.peek() != "("))
					{
						// Remove element until not get open parentheses
						record.pop();
					}
					if (record.isEmpty())
					{
						// Expression are not valid
						return;
					}
					record.pop();
				}
			}
			else
			{
				record.push(exp[i]);
			}
			i += 1;
		}
		// Display given expression
		print("\n Expression : ", expression, terminator: "");
		if (result == true)
		{
			print("\n Redundant parentheses exists", terminator: "");
		}
		else
		{
			print("\n Redundant parentheses not exists", terminator: "");
		}
	}
}
func main()
{
	let task: Redundant = Redundant();
	// Test 
	task.isRedundantParentheses("(a+b-(c + ((a+b))))");
	task.isRedundantParentheses("((a+b) -(b-(c*d)))");
	task.isRedundantParentheses("((a+b) + (c+a))");
	task.isRedundantParentheses("(a+b) + ((c))");
}
main();

Output

 Expression :  (a+b-(c + ((a+b))))
 Redundant parentheses exists
 Expression :  ((a+b) -(b-(c*d)))
 Redundant parentheses not exists
 Expression :  ((a+b) + (c+a))
 Redundant parentheses not exists
 Expression :  (a+b) + ((c))
 Redundant parentheses exists
import java.util.Stack;
/*
    Kotlin program for
    Check redundant parentheses in an expression
*/
class Redundant
{
	fun isRedundantParentheses(exp: String): Unit
	{
		// Assume given expres  
		var n: Int = exp.length;
		// Create an empty record 
		var record: Stack < Char > = Stack < Char > ();
		// Result indicator
		var result: Boolean = false;
		var i: Int = 0;
		// Execute loop through by size of n and until result is No
		while (i < n && result == false)
		{
			if (exp.get(i) == ')')
			{
				if (record.empty())
				{
					// Expression are not valid
					return;
				}
				else if (record.peek() == '(')
				{
					result = true;
				}
				else
				{
					while (record.empty() == false && record.peek() != '(')
					{
						// Remove element until not get open parentheses
						record.pop();
					}
					if (record.empty())
					{
						// Expression are not valid
						return;
					}
					record.pop();
				}
			}
			else
			{
				record.push(exp.get(i));
			}
			i += 1;
		}
		// Display given expression
		print("\n Expression : " + exp);
		if (result == true)
		{
			print("\n Redundant parentheses exists");
		}
		else
		{
			print("\n Redundant parentheses not exists");
		}
	}
}
fun main(args: Array < String > ): Unit
{
	val task: Redundant = Redundant();
	// Test 
	task.isRedundantParentheses("(a+b-(c + ((a+b))))");
	task.isRedundantParentheses("((a+b) -(b-(c*d)))");
	task.isRedundantParentheses("((a+b) + (c+a))");
	task.isRedundantParentheses("(a+b) + ((c))");
}

Output

 Expression : (a+b-(c + ((a+b))))
 Redundant parentheses exists
 Expression : ((a+b) -(b-(c*d)))
 Redundant parentheses not exists
 Expression : ((a+b) + (c+a))
 Redundant parentheses not exists
 Expression : (a+b) + ((c))
 Redundant parentheses exists


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