⚙️ 알고리즘/문제풀이

[Python] 백준 1283

dev_zoe 2025. 6. 1. 00:05
반응형

1. 문제 - 백준 1283

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

 

✅ 풀이

n = int(input())
keys = []

for _ in range(n):
  words = input()
  answer = ""
  
  for i, w in enumerate(words):
    # 1. 단어의 첫글자가 이미 단축키로 지정되어있는지 확인하고
    # 여기서 단축키는 대소문자를 구분하지 않으므로 upper 혹은 lower로 통일하여 key 리스트에 추가한다.
    if (i == 0 and w.upper() not in keys) or (words[i-1] == " " and w.upper() not in keys) and "[" not in answer:   
      # "[" not in answer는 이미 단축키를 지정했는지 여부와 같은 알파벳일 때 여러번 []를 출력하지 않기 위함 (예를들어 a가 단축키인데 aaa면 [a]aa 이런식으로 출력되어야함)
      keys.append(w.upper())    # 단축키로 지정한다.
      answer += "[" + w + "]"
    else:
      answer += w    # 단축키가 아닌 단어들은 그대로 출력

  if "[" in answer:         # 단축키가 지정되었다면 출력하고 다음으로 넘어감
    print(answer)
    continue

  answer = ""

  for w in words:
    # 2. 왼쪽에서부터 차례대로 알파벳을 보면서 단축키로 지정 안된것이 있는지 확인하고,
    if w.isalpha() and w.upper() not in keys and "[" not in answer:
      keys.append(w.upper())    # 단축키로 지정할 수 있는게 있다면 추가한다.
      answer += "[" + w + "]"
    else:
      answer += w

  if "[" in answer:
    print(answer)
    continue

  print(words)     # 3. 어떠한 것도 단축키로 지정할 수 없다면 그대로 출력한다.

 

 

✅ 다른 사람 풀이

n = int(input())
options = [input() for _ in range(n)]

used_shortcuts = set()

for option in options:
    words = option.split()   # 단어가 공백마다 구분되어있으므로 단어마다 구분
    found = False
    # 1. 단어의 첫 글자 검사
    for i, word in enumerate(words):
        key = word[0].upper()    # 대소문자 구분없으므로 upper로 통일
        if key not in used_shortcuts:   # 첫 단어가 단축키로 되어있지 않으면, 추가하고
            used_shortcuts.add(key)
            words[i] = f"[{key}]{word[1:]}"   # 해당 단어에 [단축키]를 추가하여 갈아낌
            print(' '.join(words))    # 공백마다 구분되어있으므로 공백을 포함하여 출력
            found = True
            break
    if found:
        continue
    # 2. 전체 문자열에서 왼쪽부터 하나씩 검사
    for idx, ch in enumerate(option):
        if ch == ' ':
            continue
        key = ch.upper()
        if key not in used_shortcuts:
            used_shortcuts.add(key)
            print(option[:idx] + f"[{ch}]" + option[idx+1:])
            found = True
            break
    if not found:    # 위 두가지 방법으로 단축키를 찾을 수 없다면, 아무것도 하지않고 그냥 출력함
        print(option)

 

 

반응형