Saturday, 25 January 2014

UVa Problem ID 673 (Parentheses Balance)


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;

public class Main
{
	public static void main(String[] args) throws IOException
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String input;
		StringBuffer sb = new StringBuffer("");
		int testcases = Integer.parseInt(br.readLine());

		for (int i = 0; i < testcases; i++)
		{
			boolean iscorrect = true;
			input = br.readLine();
			Stack st = new Stack();
			for (int j = 0; j < input.length(); j++)
			{
				if (iscorrect)
				{
					switch (input.charAt(j))
					{
						case '(':
						{
							st.push('(');
							break;
						}
						case '[':
						{
							st.push('[');
							break;
						}
						case ']':
						{
							if(st.isEmpty())
							{
								iscorrect=false;
								break;
							}
							char c = st.pop();
							if (c != '[')
							{
								iscorrect = false;
							}
							break;
						}
						case ')':
						{
							if(st.isEmpty())
							{
								iscorrect=false;
								break;
							}
							char c = st.pop();
							if (c != '(')
							{
								iscorrect = false;
							}
							break;
						}
					}
				}
			}
			if(iscorrect && st.isEmpty())
				sb.append("Yes");
			else
				sb.append("No");
			sb.append("\n");
		}
		System.out.print(sb);
	}

}

Previous Post
Next Post

0 comments:

Advertisement