땅지원
땅지원's Personal blog
땅지원
전체 방문자
오늘
어제
  • 전체 (353)
    • Frontend (2)
      • React (2)
    • Backend (90)
      • Java (16)
      • Python (19)
      • Spring (23)
      • Database (21)
      • Troubleshooting (8)
    • DevOps (27)
      • ELK (13)
    • CS (40)
    • OS (2)
      • Linux (2)
    • Algorithm (95)
      • concept (18)
      • Algorithm Problem (77)
    • 인공지능 (25)
      • 인공지능 (12)
      • 연구노트 (13)
    • 수업정리 (35)
      • 임베디드 시스템 (10)
      • 데이터통신 (17)
      • Linux (8)
    • 한국정보통신학회 (5)
      • 학술대회 (4)
      • 논문지 (1)
    • 수상기록 (8)
      • 수상기록 (6)
      • 특허 (2)
    • 삼성 청년 SW 아카데미 (6)
    • 42seoul (12)
    • Toy project (3)
    • 땅's 낙서장 (2)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

  • 20.11.6 BB21플러스 온라인 학술대회
  • 20.10.30 한국정보통신학회 온라인 학술대회

인기 글

태그

  • ㅗ
  • D
  • E
  • I
  • 이것이 리눅스다 with Rocky Linux9

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
땅지원

땅지원's Personal blog

Algorithm/Algorithm Problem

백준 1213 & 팰린드롬 알고리즘(Palindrome Algorithm)

2022. 2. 17. 17:13

Palindrome

거꾸로 읽어도 제대로 읽는 것과 같은 문장이나 낱말, 숫자, 문자열

ex) 기러기, 요기요

 

def is_palindrome(word):
    list_word = list(word)
    for i in range(0, len(list_word) // 2):

        if list_word[i] == list_word[len(list_word) - 1 - i]:
            continue
        else:
            return False

    return True

slice를 이용하여 문자열을 반대로 뒤집은다음에 비교를 하는것도 매우 좋은 방법이다.

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

 

1213번: 팰린드롬 만들기

첫째 줄에 문제의 정답을 출력한다. 만약 불가능할 때는 "I'm Sorry Hansoo"를 출력한다. 정답이 여러 개일 경우에는 사전순으로 앞서는 것을 출력한다.

www.acmicpc.net

처음에는 팰린드롬의 정의를 이용하여 함수를 만들고 입력받은 문자열의 표현가능한 순서들을 순열로 뽑아내 판단하였다

 

def ispalindrome(data):
    data_reverse = data[::-1]
    if data == data_reverse:
        return 1
    else:
        return 0

data = input()
res = []
from itertools import permutations
for i in permutations(data,int(len(data))):
    temp = ''
    if ispalindrome(i):
        for j in range(int(len(data))):
            temp += i[j]
        res.append(temp)
if len(res) == 0:
    print("I'm Sorry Hansoo")
else:
    print(min(res))

하지만 시간초과가 나면서 다른 방법을 생각해야 했다.

 

좀 더 그리디 알고리즘적으로 접근을 해보면 각 알파벳은 짝수가 되어야 팰린드롬이 될 수 있으며

만약 홀수 알파벳이 1개는 괜찮지만 2개이상이 되면 그 문자열은 팰린드롬이 될 수 없다..

import sys
from collections import Counter

word = list(map(str, sys.stdin.readline().strip()))
word.sort()
check = Counter(word)
cnt = 0
center = ""

for i in check:
    if check[i] % 2 != 0:
        cnt += 1
        center += i
        word.remove(i)
    if cnt > 1:
        break
if cnt > 1:
    print("I'm Sorry Hansoo")
else:
    res = ""
    for i in range(0, len(word), 2):
        res += word[i]
    print(res + center + res[::-1])

Collections 모듈의 Counter 클래스를 활용하여 쉽게 홀/짝수 알파벳을 구할 수 있다.

from collections import Counter
check = Counter(word)

Counter({'B': 4, 'A': 3, 'S': 2, 'D': 1})

마지막 출력은 팰린드롬 형태의 문자열을 출력해야 하기 때문에  짝수만 저장되어있는 list에서 2칸 간격으로 저장 한것을 

원본 + 중간 + 원본_reverse 형태로 출력을 하면 팰린드롬 형태로 만들어진다.

 

'Algorithm > Algorithm Problem' 카테고리의 다른 글

백준 2667 단지번호붙이기(BFS, DFS)  (0) 2022.03.06
백준 18111 마인크래프트  (0) 2022.02.17
백준 1251 단어 나누기  (0) 2022.02.17
백준 1991 트리 순회  (0) 2022.02.17
Python Asterisk(*) 사용 용도  (0) 2022.01.03
    'Algorithm/Algorithm Problem' 카테고리의 다른 글
    • 백준 2667 단지번호붙이기(BFS, DFS)
    • 백준 18111 마인크래프트
    • 백준 1251 단어 나누기
    • 백준 1991 트리 순회
    땅지원
    땅지원
    신입 개발자의 우당탕탕 기술 블로그

    티스토리툴바