본문 바로가기
백준 풀이

[백준 풀이_Java] 15881 Pen Pineapple Apple Pen

by happyhelen 2021. 8. 29.

 

 

 

 

내가 푼 방법

 

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

public class Main {

	public static void main(String[] args) throws IOException {
		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		String str = br.readLine();
		String ex;
		int count =0;
		// pPAp
		
		for(int i=0; i<=n-4; i++) {
        
			// substring 으로 자르고
			ex = str.substring(i, i+4);
			
            // 일치하면 i를 4 미뤄준다(같은 p가 두 pPAp에 들어갈 수 없다는 조건)
			if(ex.equals("pPAp")) {
				count++;
				i += 3; // coutinue; 하면 자동으로 i는 1 증가되므로 3만 더해주면 된다
				continue;
			}else continue;
		}
		
		System.out.println(count);

	}

}

 

이번에 틀렸던 이유는 i에 얼마를 더하느냐에 있었다

반복문이 돌면서 i는 자동으로 증가하는데 i 가 결론적으로 4 증가하도록 하려면 반복문 안에서는 3 만 증가시켜주면 된다