Write a program that examines a string of characters and determines if all openi
ID: 3671880 • Letter: W
Question
Write a program that examines a string of characters and determines if all opening bracket characters such as (, [, or { are matched with their correct closing characters. Use a stack to do this. The basic algorithm is as follows:
Read the string, character by character.
If the character is an opening bracket character, push its equivalent closing character onto the stack.
If the character is a closing bracket character, pop the stack, and see if the character you popped matches the current character. If not, the brackets in the string are not paired correctly.
If the character is not a bracket character, ignore it.
If you get through the whole string without failing, check to see if the stack is empty. If it is, the brackets are all matched correctly. If not, the brackets were not matched correctly.
Your program should print a message back to the user if the brackets are correctly matched or not
Test your program on some small strings. Once it is working properly, it should work regardless of the string. Try using it on an entire Java source code file.
Explanation / Answer
public class ValidParanthesis {
public static void main(String args[]){
String exp1= "{{([])}}";
System.out.println("Is Valid "+exp1+" : "+IsValid(exp1));
}
private static boolean IsValid(String exp1) {
if( exp1 == null)
return true;
Stack<character> st = new Stack<character>();
for(int i=0; i < exp1.length() ; i++){
char t = exp1.charAt(i);
if( t == '{' || t == '[' || t== '('){
st.push(t);
}else{
char opp;
if( t== '}')
opp='{';
else
if( t == ']')
opp ='[';
else
opp='(';
if( st.empty() || st.pop() != opp)
return false;
}
}
return st.isEmpty();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.