다양한 단어란 모두 다른 알파벳 소문자로만 이루어진 단어를 의미한다. 예를 들어, "codeplus", "coding", "algorithm"은 다양한 단어, "baekjoon", "startlink"는 다양한 단어가 아니다.
다양한 단어 S가 주어졌을 때, 사전 순으로 S의 바로 다음에 오는 다양한 단어를 구해보자.
첫째 줄에 길이가 26보다 작거나 같은 다양한 단어 S가 주어진다.
사전 순으로 S의 바로 다음에 오는 다양한 단어를 출력한다. 바로 다음에 오는 단어가 없는 경우에는 -1을 출력한다.
codeplus
codeplusa
import sys
"""
모두 다른 알파벳 소문자로만 이루어진 단어.
26자리 이하
"""
def make_next_sentence(word):
if len(word) < 26:
for ch in 'abcdefghijklmnopqrstuvwxyz':
if ch not in word:
return word + ch
for i in range(25, -1, -1):
prefix = word[:i]
for ch in "abcdefghijklmnopqrstuvwxyz":
if ch > word[i] and ch not in prefix:
return prefix + ch
return '-1'
def main():
inputs = sys.stdin.read().rstrip()
sys.stdout.write(make_next_sentence(inputs))
if __name__ == "__main__":
main()
26자리 이하는 쉬운데 26자리에서 해맸다. 난 이렇게 구현 했지만, c++에는 다음 순열(next permutation) 알고리즘이 있다고 한다. 참고 바람
4등했는데도 먼가 찝찝함.
import sys
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
def next_diverse_word(word: str) -> str:
"""
주어진 단어(word)가 모두 다른 알파벳 소문자로 이루어져 있을 때,
사전 순으로 바로 다음에 오는 '다양한 단어'를 반환한다.
만약 다음 단어가 존재하지 않으면 '-1'을 반환한다.
"""
# 단어 길이가 26자리 미만이면, 사용하지 않은 가장 작은 문자를 뒤에 붙인다.
if len(word) < 26:
used = set(word)
for ch in ALPHABET:
if ch not in used:
return word + ch
# 단어가 26자리인 경우, 뒤에서부터 문자를 변경할 수 있는 위치를 찾는다.
for i in range(len(word) - 1, -1, -1):
prefix = word[:i]
used_prefix = set(prefix)
# 현재 위치의 문자보다 큰 문자 중, prefix에 없는 가장 작은 문자를 찾는다.
for ch in ALPHABET:
if ch > word[i] and ch not in used_prefix:
return prefix + ch
return "-1"
def main():
word = sys.stdin.read().rstrip()
result = next_diverse_word(word)
sys.stdout.write(result)
if __name__ == "__main__":
main()