In: Computer Science
Write a method called isMatch that takes a string of parentheses and check if all parentheses match correctly. The parameter string might consist of other characters. Ignore other characters, just check the () {} [] public static boolean isMatch(String expressionLine); Use a JCF ArrayDeque or LinkedList as a stack to store all open or left parentheses.
Use following main method to check your method.
public static void main(String[] args)
{
String[] expression = new String[]{"{5*(x+2)+(y-1);}", "32*(20+(x[i]*3)-1", "((){([][])})", "({}((0))", "{([]})", "{}())", "{"};
for (String st: expression) System.out.println(st + " is " + isMatch(st));
}
Stack.java
import java.util.LinkedList;
public class Stack {
private LinkedList<Character> list = new LinkedList<>();
public void push(char ch) {
list.add(ch);
}
public char pop() {
if (list.isEmpty()) {
System.out.println("Underflow error");
return
'\0';
} else {
int size = list.size();
char ch =
list.get(size - 1);
list.remove(size
- 1);
return ch;
}
}
public LinkedList<Character> getList()
{
return list;
}
public void setList(LinkedList<Character>
list) {
this.list = list;
}
}
Paranthesis.java
public class Paranthesis {
static boolean isMatch(String str) {
char[] arr = str.toCharArray();
Stack stack = new Stack();
for (int i = 0; i < arr.length; i++) {
if (arr[i] ==
'{' || arr[i] == '(' || arr[i] == '[')
stack.push(arr[i]);
//System.out.println(stack.getList().toString());
if (arr[i] == '}' || arr[i] == ')' || arr[i] == ']') {
if (stack.getList().isEmpty()) {
return false;
}
else {
char ch = stack.pop();
//System.out.println("Stack
pop is " + ch);
//System.out.println("Array
is " + arr[i]);
if (ch == '(' &&
arr[i] == ')')
continue;
else if (ch == '{' &&
arr[i] == '}')
continue;
else if (ch == '[' &&
arr[i] == ']')
continue;
else
return
false;
}
}
}
if
(stack.getList().isEmpty())
return
true;
else {
return
false;
}
}
public static void main(String[] args) {
// TODO Auto-generated method
stub
String[] expression = new
String[] { "{5*(x+2)+(y-1);}", "32*(20+(x[i]*3)-1", "((){([][])})",
"({}((0))",
"{([]})", "{}())", "{" };
for (String string :
expression)
System.out.println(string + " is " + isMatch(string));
}
}
Output
{5*(x+2)+(y-1);} is true
32*(20+(x[i]*3)-1 is false
((){([][])}) is true
({}((0)) is false
{([]}) is false
{}()) is false
{ is false
Feel free to ask any doubts, if you face any difficulty in understanding.
Please upvote the answer if you find it
helpful