프로그래머스(Programmers)

Level 3 > 가장 긴 팰린드롬

cepiloth 2018. 8. 22. 13:22
반응형

https://programmers.co.kr/learn/courses/30/lessons/12904?language=cpp


1. 문제

주어진 문자열에서 가장 긴 펠린드롬 문자열을 찾는 문제


2. 알고리즘

키워드 - 문자열, 브루트포스


3. 코드


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
#include <iostream>
#include <string>
#include <algorithm>
 
using namespace std;
int solution(string s)
{
    int answer = 0;
    int length = s.length();
 
    for(int i=0;i<length;i++) {
        for(int subLength = length; subLength >answer; subLength--) {
            int left = i;
            int right = left+subLength - 1;
            while(left<right && s[left] == s[right]) {
                left++;
                right--;
            }
            if(left >= right && answer < subLength) {
                answer = subLength;
                break;
            }
        }
    }
 
    return answer;
}
cs

반응형