※ 글쓴이는 취미로 코딩을 익혀보는 사람이라 정확하지 않은 내용을 담고 있을 수 있다 ※

 

이번에 볼 문제는 백준 26201번 문제인 Finding Maximal Non-Trivial Monotones이다.
문제는 아래 링크를 확인하자.

https://www.acmicpc.net/problem/26201 

 

26201번: Finding Maximal Non-Trivial Monotones

The input consists of two lines. The first line contains a single integer $N$, where $1 ≤ N ≤ 10^5$. The second line contains a string with exactly $N$ characters, composed only of the characters “a” and “b”.

www.acmicpc.net

주어진 문자열에서, 연속해서 둘 이상의 'a'가 붙어있는 maximal한(maximum이 아니다) 부분문자열(substring)의 길이의 합을 구하는 문제이다.

 

문자열을 살피면서 연속한 'a'의 개수를 세고, 더 연속하게 이어나갈 수 없는 경우 지금까지 이어진 개수가 둘 이상이라면 문제의 답을 나타내는 변수에 더해나가는 것으로 문제를 해결할 수 있다.

 

아래와 같이 문자열의 끝에 'b'를 하나 추가하면 별도의 예외처리 없이 간편하게 문제를 해결할 수 있다.

 

아래는 제출한 소스코드이다.

#include <iostream>
#include <string>
using namespace std;

int slen;
string s;
int ans;

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);

	cin >> slen >> s;
	s += "b";

	int combo = 0;
	for (auto& l : s) {
		if (l == 'a') combo++;
		else {
			if (combo > 1) ans += combo;
			combo = 0;
		}
	}

	cout << ans;
}
728x90

+ Recent posts