62,629
社区成员
发帖
与我相关
我的任务
分享import java.util.*;
import java.util.Scanner;
import java.util.Stack;
import java.io.File;
public class test
{
private static int i;
private static final char LEFTPARENT = '(';
private static final char RIGHTPARENT = ')';
private static final char LEFTBRACE = '{';
private static final char RIGHTBRACE = '}';
private static final char LEFTBRACKET = '[';
private static final char RIGHTBRACKET = ']';
public static boolean isBalanced(String s)
{
Stack<E> stack = new Stack<E>();
for (i = 0; i < s.length(); i++)
{
if (s.charAt(i) == LEFTPARENT) stack.push(LEFTPARENT);
else if (s.charAt(i) == LEFTBRACE) stack.push(LEFTBRACE);
else if (s.charAt(i) == LEFTBRACKET) stack.push(LEFTBRACKET);
else if (s.charAt(i) == RIGHTPARENT)
{
if (stack.isEmpty())
return false;
if (stack.pop() != LEFTPARENT)
return false;
}
else if (s.charAt(i) == RIGHTBRACE)
{
if (stack.isEmpty())
return false;
if (stack.pop() != LEFTBRACE)
return false;
}
else if (s.charAt(i) == RIGHTBRACKET)
{
if (stack.isEmpty())
return false;
if (stack.pop() != LEFTBRACKET)
return false;
}
}
return stack.isEmpty();
}
public static void main(String args[])
{
Scanner reader = new Scanner(new File("data.txt"));
while (reader.hasNext()){
int s = reader.nextInt();
System.out.println(i);
}
{
if (isBalanced(s))
System.out.println("The grouping symbols in"+" \""+ s +"\" "+"match");
else
System.out.println("The grouping symbols in"+" \""+ s +"\" "+ "do not match");
System.out.println();
}
}
}