What's new

Help Java Program about stack

sana may makasagot nito.

Enter string -> (x-2 * (x+7))
output balance

enter string -> ((x+6 * (x-4) + (x+3)
output notbalance

algo

scan all characters in the string
if open parenthesis "(" push to stack
if close parenthesis ")" push to pop

after scanning
if stack is empty = balance
if stack is not empty = not balance

may nakita akong mga code sa google:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* Balanced Brackets Problem - You do not have permission to view the full content of this post. Log in or register now.
*/
import java.util.Stack;

public class ParenthesesChecker {

public static void main(String[] args) {

String str = "{[]})";

//Declare a stack
Stack st = new Stack<>();

//Traverse a string
for(int i = 0; i < str.length(); i++) {

/* If the current character is starting bracket,
then push them in a stack
*/
if(str.charAt(i) == '{' || str.charAt(i) == '[' || str.charAt(i) == '(') {
st.push(str.charAt(i));

/*
Else, If the stack is not empty,
And current character is a closing bracket
and top character of a stack is matching open bracket
then pop it.
*/
} else if ( !st.empty() && ((str.charAt(i) == ']' && st.peek() == '[') ||
(str.charAt(i) == '}' && st.peek() == '{') ||
(str.charAt(i) == ')' && st.peek() == '('))) {

st.pop();

} else {
st.push(str.charAt(i));
}
}

if(st.empty()) {
System.out.println("Balanced");
} else {
System.out.println("Not balanced");
}
}
}

(tanong ko lang pano po to ma work need po ba gumawa ng new class na ParenthesisChecker.java? ano naman ang ilalagay sa main.java)
 
Last edited:

Similar threads

Back
Top