흙금이네 블로그

[BOJ] 15927 - 회문은 회문아니야!! (Python, JavaScript) 본문

알고리즘

[BOJ] 15927 - 회문은 회문아니야!! (Python, JavaScript)

흙금 2023. 6. 18. 11:55

 

 

아이디어

 

회문인 문자열을 구성하는 문자가 하나라면 -1, 두 문자 이상이라면 문자열의 길이보다 1 작은 값을 출력한다.

 

 

풀이 #1 (Python)

 

def solution():
    S = input()
    N = len(S)
    if S[:N//2] != S[N//2+N%2:][::-1]:
        print(N)
    elif S != S[0]*N:
        print(N-1)
    else:
        print(-1)

solution()

 

 

 

풀이 #2 (JavaScript)

 

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().split('\n');

function solution() {
    
    function isPalindrome() {
        for (let i=0; i<N/2+N%2; i++) {
            if (S[i] !== S[N-i-1]) return false;
        }
        return true;
    }
    
    const S = input[0];
    const N = S.length;
    if (!isPalindrome()) console.log(N);
    else if (S !== S[0].repeat(N)) console.log(N-1);
    else console.log(-1);
}

solution();

 

Comments