the other ocdeSolutionpublic class ParenBalance public stat
the other ocde:
Solution
public class ParenBalance {
public static boolean parensCorrect(ProperStack stack, String line) {
for (Character c : line.toCharArray()) {
if (c == \'{\' || c == \'(\' || c == \'[\')
{
stack.push(c);
}
if (c == \'}\' || c == \')\' || c == \']\')
{
if (stack.isEmpty())
return false;
char last = (char )stack.peek();
if (c == \'}\' && last == \'{\' || c == \')\' && last == \'(\' || c == \']\' && last == \'[\')
stack.pop();
else
return false;
}
}
return stack.isEmpty();
}
public static void main(String args[]) {
ProperStack ps = new ProperStack();
if(parensCorrect(ps, \"{()}\") == true){
System.out.println(\"{()} is balanced \");
}else{
System.out.println(\"{()} is unbalanced \");
}
if(parensCorrect(ps, \"{}()}\") == true){
System.out.println(\"{}()} is balanced \");
}else{
System.out.println(\"{}()} is unbalanced \");
}
if(parensCorrect(ps, \"[[[]]]{()}\") == true){
System.out.println(\"[[[]]]{()} is balanced \");
}else{
System.out.println(\"[[[]]]{()} is unbalanced \");
}
}
}
import java.util.EmptyStackException;
import java.util.Stack;
/**
* Class which wraps Java\'s built-in {@link Stack} implementation, but removes
* all of the methods that are inapproprate for a Stack.
*
* @author Matthew Hertz
* @param Type of data stored within this Stack.
*/
public class ProperStack<E> {
/** The actual Stack in which all the elements will be stored. */
private Stack store;
/** Create a new (empty) instance of this class. */
public ProperStack() {
store = new Stack<>();
}
/**
* Pushes an item onto the top of this stack. Traditionally, this is the only
* method available to add data to a Stack.
*
* @param item Element to be added to the top of the stack.
* @return Element added to the Stack (e.g., {@code item}).
*/
public E push(E item) {
return (E)store.push(item);
}
/**
* Removes and returns the element at the top of this stack. Traditionally,
* this is the only method available to remove data from the Stack.
*
* @return Element that was removed from the top of the stack.
* @throws EmptyStackException Thrown when the Stack does not have any
* elements to remove.
*/
public E pop() {
return (E)store.pop();
}
/**
* Like {@link #pop()}, this returns the element at the top of the stack, but
* unlike {@link #pop} this method DOES NOT remove it from the stack.
*
* @return Element that is at the top of the stack.
* @throws EmptyStackException Thrown when the Stack does not have any
* elements to remove.
*/
public E peek() {
return (E)store.peek();
}
/**
* Returns the number of elements in this Stack.
*
* @return Items available in the Stack.
*/
public int size() {
return store.size();
}
/**
* Returns whether there are any elements in this Stack.
*
* @return True if the Stack does not have any elements; false otherwise.
*/
public boolean isEmpty() {
return store.isEmpty();
}
/**
* Removes all the elements from the Stack.
*/
public void clear() {
store.clear();
}
}


