1028. 語句匹配(java)

https://acm.sjtu.edu.cn/OnlineJudge/problem/1028

Description
Pascal語言中,複合語句用begin...end表示,條件語句用if...then...else...表示,其中,else子句可以出現也可以不出現。現在提取出一些語句中的所有begin、end、if、then、else,編寫一個程序檢查它們能否匹配,以構成若干條合法的語句。

Input Format
輸入包含兩行。

第1行:一個整數N,表示接下來有N個字符串將讀入。

第2行:包含N個字符串,每個字符串一定是{"begin","end","if","then","else"}之一(不包括引號)。這些字符串表示從一系列語句中依次提取出的所有元素。

Output Format
若輸入可以構成若干條合法語句,輸出一行"YES",否則輸出一行"NO"。(不包含引號)

Sample Input
9
if then begin if then begin end end else
Sample Output
YES
Sample Input
4
if begin end then
Sample Output
NO
說明
N
≤
100
注意begin...end不能作爲判斷條件。(見樣例2)

注意then與else之後都允許出現不止一條if語句或複合語句。

感謝聶步青提供加強數據。

只能過90%

import java.util.*;
import java.io.*;
import java.text.*;
import java.math.*;
public class Main{
	public static void main(String[] args) {
		try {
    		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    		int n = Integer.parseInt(br.readLine());
    		String[] parts = br.readLine().split(" ");
    		Stack<String> s1 = new Stack<>();
    		Stack<String> s2 = new Stack<>();
    		boolean isif = false;
    		boolean isbegin = false;
    		for(int i = 0; i < n; i++) {
    			if(parts[i].charAt(0) == 'i') {
    				if(!s1.isEmpty()) {
    					if(s1.peek().contentEquals("then")) {
    						s1.pop();
    						s1.pop();
    					}
    				}
    				isif = true;
    				s1.push("if");
    			}
    			else if(parts[i].charAt(0) == 'b') {
    				if(isif) {
    					isbegin = true;			
    				}
    				s2.push("begin");
    			}
    			else if(parts[i].charAt(0) == 't') {
    				if(s1.isEmpty()||!s1.peek().contentEquals("if")) {
    					System.out.println("NO");
    					return;
    				}
    				s1.push("then");
    				isif = false;
    			}
    			else if(parts[i].charAt(1) == 'l') {
    				if(s1.isEmpty()||!s1.peek().contentEquals("then")) {
    					System.out.println("NO");
    					return;
    				}
    				s1.pop();
    				if(s1.isEmpty()||!s1.pop().contentEquals("if")) {
    					System.out.println("NO");
    					return;
    				}
    			}
    			else {
    				if(s2.isEmpty()||!s2.pop().contentEquals("begin")) {
    					System.out.println("NO");
    					return;
    				}    
    				if(isif&&isbegin) {
    					System.out.println("NO");
    					return;
    				} 
    			}
    		}
			if(!s1.isEmpty()) {
				if(s1.peek().contentEquals("then")) {
					s1.pop();
					s1.pop();
				}
			}
    		if(!s1.isEmpty()&&s1.peek().equals("if")) {
				System.out.println("NO");
				return;    			
    		}    		
    		if(!s2.isEmpty()) {
				System.out.println("NO");
				return;    			
    		}
			System.out.println("YES");
		} catch(IOException e) {
			e.printStackTrace();
		}
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章