Algorithm & Problem Solving/구현(Implementation)

[백준 9081] 단어 맞추기 (Python)

baby_ohgu 2021. 1. 22. 19:51

www.acmicpc.net/problem/9081

 

9081번: 단어 맞추기

입력의 첫 줄에는 테스트 케이스의 개수 T (1 ≤ T ≤ 10)가 주어진다. 각 테스트 케이스는 하나의 단어가 한 줄로 주어진다. 단어는 알파벳 A~Z 대문자로만 이루어지며 항상 공백이 없는 연속된 알

www.acmicpc.net

 

문제풀이

 

단순 구현문제로, next_permutation 함수를 이용하여 쉽게 해결할 수 있다.

 

코드

import sys

def next_permutation(a):
    i = len(a) - 1
    while i > 0 and a[i - 1] >= a[i]:
        i -= 1
    if i <= 0: return False
    j = len(a) - 1
    while a[i - 1] >= a[j]:
        j -= 1
    a[i - 1], a[j] = a[j], a[i - 1]
    j = len(a) - 1
    while i < j:
        a[i], a[j] = a[j], a[i]
        i += 1
        j -= 1
    return True

if __name__ == '__main__':
    for _ in range(int(input())):
        arr = list(map(str, sys.stdin.readline().rstrip()))
        next_permutation(arr)
        print(''.join(map(str, arr)))

 

결과

 

문제풀이나 코드에서 이상한 부분 지적은 언제나 환영합니다!