피너클의 it공부방

백준 15927 회문은 회문아니야 (c++) : 피너클 본문

백준

백준 15927 회문은 회문아니야 (c++) : 피너클

피너클 2025. 9. 13. 01:30
728x90
반응형

15927번: 회문은 회문아니야!!

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

 

그냥 풀었다.

 

가장 긴 팰린드롬이 아닌 문자열을 구하는 것이니 아주 간단하게 생각했다.

 

만약 주어진 문자열이 팰린드롬이 아니라면? 주어진 문자열의 길이를 출력하면 된다.

만약 주어진 문자열이 팰린드롬이라면? 주어진 문자열의 길이 -1 을 출력하면 된다.

 

팰린드롬에서 하나를 뺏는데도 팰린드롬인 경우는 전부 같은 문자인 경우밖에 없다.

이 경우는 따로 빼줬다.

 

	cin >> str;

	int len = str.length();
	char c = str[0];
	bool chk = true;
	for (int i = 0; i < str.length(); i++) {
		if (c != str[i]) {
			chk = false;
			break;
		}
	}

	if (chk) {
		cout << -1 << '\n';
	}

전부 같은 문자인지 확인해주고 맞다면 -1을 출력한다.

 

	else {
		int start = 0, end = len - 1;
		chk = true;
		while (start <= end) {
			if (str[start] != str[end]) {
				chk = false;
				break;
			}
			start++;
			end--;
		}

		if (chk) cout << len - 1 << '\n';
		else cout << len << '\n';
	}

	return 0;
}

아니면 팰린드롬인지 확인해주고

팰린드롬이면 길이-1, 아니면 길이를 출력한다.

 

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>

using namespace std;

string str;

int main(int argc, char** argv)
{
	std::ios_base::sync_with_stdio(false);
	std::cin.tie(NULL);

	cin >> str;

	int len = str.length();
	char c = str[0];
	bool chk = true;
	for (int i = 0; i < str.length(); i++) {
		if (c != str[i]) {
			chk = false;
			break;
		}
	}

	if (chk) {
		cout << -1 << '\n';
	}
	else {
		int start = 0, end = len - 1;
		chk = true;
		while (start <= end) {
			if (str[start] != str[end]) {
				chk = false;
				break;
			}
			start++;
			end--;
		}

		if (chk) cout << len - 1 << '\n';
		else cout << len << '\n';
	}

	return 0;
}

전체코드다.

728x90
반응형
Comments