JAVA JAVA JAVA JAVA Write a program that checks whether or not a string of chara
ID: 3671263 • Letter: J
Question
JAVA JAVA JAVA JAVA
Write a program that checks whether or not a string of characters that has enclosing symbols are well-formed. Enclosing meaning there is an open version of the symbol it and a closing symbol. Furthermore, well-formed means that if there is an opening symbol, then there must be a matching closing symbol also in the string.
The symbols to check are:
Parenthesis: ()
Double Quotes: “”
Curly Brackets / Braces: {}
Angle Brackets: <>
Write a stack, and use it to solve this problem
You may NOT use the built-in java stack
You may either implement the stack as a linked structure or an array. If you use an array assume the max size is 100;
Write another class that has a method which takes in a string and returns a Boolean that corresponds to whether or not the string is well formed. Use the following algorithm to determine if the string is well-formed.
Algorithm overview:
Examine each character one-by-one
If the character is the opening version of one of the enclosing symbols, then push that character onto the stack
If the character is the closing version of one of the enclosing symbols, then pop and check if it matches. If it does continue, but if not or if the stack is empty return false.
If there is a symbol that is not one of the enclosing symbols then ignore it
After each character has been process if the stack is empty return true. Otherwise return false
Finally write a class (it could be the same class as the class above) which uses a main method to test the following conditions:
() – should return true
<<<>>> - should return true
{(“tacos”)} – should return true
if(pass == true){return “yay!”;} – should return true
abcd – should return true
“””– should return false
<(“) – should return false
:-) – should return false
<3 – should return false
(<{“”}> - should return false
Explanation / Answer
#include<iostream>
#include<stack>
#include<string>
using namespace std;
bool ArePair(char opening,char closing)
{
if(opening == '(' && closing == ')') return true;
else if(opening == '{' && closing == '}') return true;
else if(opening == '[' && closing == ']') return true;
return false;
}
bool AreParanthesesBalanced(string exp)
{
stack<char> S;
for(int i =0;i<exp.length();i++)
{
if(exp[i] == '(' || exp[i] == '{' || exp[i] == '[')
S.push(exp[i]);
else if(exp[i] == ')' || exp[i] == '}' || exp[i] == ']')
{
if(S.empty() || !ArePair(S.top(),exp[i]))
return false;
else
S.pop();
}
}
return S.empty() ? true:false;
}
int main()
{
string expression;
cout<<"Enter an expression: ";
cin>>expression;
if(AreParanthesesBalanced(expression))
cout<<"Balanced ";
else
cout<<"Not Balanced ";
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.