반응형
https://www.acmicpc.net/problem/1254
문제 해결 알고리즘
문자열의 맨 끝 두 번째부터 시작해서 첫번째 문자를 붙여가면서 각각 팰린드롬인지 확인한다. 다음부터는 시작하는 문자열을 앞으로 한 칸 당겨서 진행해준다. 그렇게 첫번째까지 완료한 후 팰린드롬인 문장 중 가장 작은 길이를 출력한다.
소스 코드
#include <bits/stdc++.h>
using namespace std;
bool isPalindrome(string str){
bool flag = true;
for(int i=0;i<str.size();i++){
if(str[i] != str[str.size()-1-i]) flag = false;
}
return flag;
}
int main(){
int result = 101;
string str; cin >> str;
if(str.size() == 1) {
cout << 1;
return 0;
}
for(int i=0;i<=str.size()-2;i++){
int cnt = str.size()-2-i;
string temp_str = str;
do{
if(isPalindrome(temp_str)){
result = min(result, int(temp_str.size()));
}
temp_str += str[cnt--];
}while(cnt >= -1);
}
cout << result;
}
반응형
'알고리즘 문제 해결 > BOJ' 카테고리의 다른 글
[백 트래킹, 브루트 포스] BOJ 1342 행운의 문자열 (0) | 2022.03.08 |
---|---|
[브루트 포스] BOJ 1105 팔 (0) | 2022.03.05 |
[BFS] BOJ 1743 음식물 피하기 (0) | 2022.02.26 |
[BFS] BOJ 1303 전쟁 - 전투 (0) | 2022.02.23 |
[브루트 포스] BOJ 16943 숫자 재배치 (0) | 2022.02.20 |