package day2;
import java.util.Scanner;
import java.util.Stack;
public class CheckBrace {
public boolean check(String stat) {
char openPair, testCh;
int idx = 0;
Stack<Character> stack = new Stack<Character>();
while (idx < stat.length()) {
testCh = stat.charAt(idx);
switch (testCh) {
case '(':
case '{':
case '[':
stack.push(testCh); break;
case ')':
case '}':
case ']':
if (stack.isEmpty())
return false;
else {
openPair = stack.pop();
if ((openPair == '(' && testCh != ')') ||
(openPair == '{' && testCh != '}')
|| (openPair == '[' && testCh != ']'))
return false;
else
break;
}
}
idx++;
}
if (stack.isEmpty())
return true;
else
return false;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("검사 할 수식 입력 : ");
String stat = scanner.next();
CheckBrace test = new CheckBrace();
if(test.check(stat)){
System.out.println(stat +"는 괄호 짝이 맞는 수식입니다.");
}else{
System.out.println(stat +"는 괄호 짝이 맞지 않는 수식입니다.");
}
}
}
'Java > 자료구조와 알고리즘' 카테고리의 다른 글
TreeMap 으로 순서정렬 알고리즘 (0) | 2017.09.07 |
---|---|
Tree set 으로 순서나열하기 <2> (0) | 2017.09.07 |
Tree set으로 순서 나열하기 <1> (0) | 2017.09.07 |
수식검사 알고리즘 (0) | 2017.09.07 |
다항식 덧샘 (0) | 2017.06.01 |