티스토리 뷰

java/BAEKJOON

java 16120번 PPAP (백준)

rofn123 2023. 3. 18. 01:50
import java.util.Scanner;

class Stack { //Stack을 클래스로 
private int top;
private char arr[] = new char[1000000];
public Stack(){top=0;}
public boolean isEmpty() { return top == 0;} //스택 비었는가? 
public void push(char e) {arr[top++] = e;} //스택 넣기 
public char pop() {return arr[--top];} //스택 꺼내기 
public int cnt() {return top;} //스택의 요소 개수 
public char peek() {return arr[top-1];} //가장 마지막에 들어간것 
};

public class Main {
	public static void main(String[] args) {
		String in;
		Scanner scan = new Scanner(System.in);
		in = scan.nextLine(); //문자열 입력 
		char c[] = new char[1000000];
		c = in.toCharArray();
		Stack s = new Stack();
		int i=0;
		boolean flag = false; 
		
		
		while(i < in.length()) { //Null 문자열 끝을 초과하면 
			if(c[i] == 'P') { //P일 경우 
				if(s.isEmpty()) s.push(c[i]); //스택이 비어있으면 넣고 
				else if(s.peek() == 'P') s.push(c[i]); //가장 마지막에 들어간 것이 P여도 넣고 
				else { //가장 마지막이 A일 경우 스택의 요소 두개를 뺀다 
					s.pop();  //PPAP -> P이므로 
					s.pop(); //PPA(스택) + P(비교하는거); 여기선 스택에서 2개를 빼고, 비교하는 것을 집어넣지 않으면 PPAP => P 을만들수 있다. 
				}
			}
			else if(c[i] == 'A') { //비교하는게 A일 경우 
				if(s.cnt() < 2) { //PPAP문자열을 만들려면 반드시 스택에 P 2개는 스택에 있어야 한다.
					flag = true; //A를 스택에 넣지 못하여 끝났음을 나타내는 플래그이다. 
					break; //더 이상 반복을 할 필요가 없다 
				}  else { //P가 스택에 이미 2개이상이면 
					s.push(c[i]); //스택에 집어넣는다 
				}
			}
			i++;
		}
		
		if(s.cnt() == 1 && s.peek() == 'P' && !flag) System.out.printf("PPAP");
		else System.out.printf("NP");
	}
}

 

 

풀이 : 스택

이 java코드는 아래의 c++을 java로 바꾼 것 입니다.

 

https://h202.tistory.com/229

 

c++ 16120번 PPAP (백준)

#include #define M 1000000 class Stack { //Stack을 클래스로 private: int top; char arr[M]; public: Stack() : top(0){} bool isEmpty() { return top == 0;} //스택 비었는가? void push(char e) {arr[top++] = e;} //스택 넣기 char pop() {return arr[

h202.tistory.com

 

최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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
글 보관함