728x90
✏️ 문제
https://www.acmicpc.net/problem/10809
✏️ 풀이방법
1. 백준 10808 알파벳개수에서 변형된 문제로 풀이는 유사하다. 다만 개수가 아닌 위치 인덱스 값을 출력한다.
2. baekj'oo'n과 같이 중복된 경우를 유의해야한다.
3. 중복을 제거하려고 set과 dict.fromkeys를 활용했지만 글자수의 길이 자체가 달라져 위치가 달라지는 문제가 발생한다.
4. 이에 contain의 초기에 집어넣은 값인 -1일때만 위치를 넣어 처음 위치의 값이 들어갈 수 있도록 하였다.
📌 코드
s = input()
alp = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
contain = [-1 for i in range(len(alp))]
for i in range(len(alp)):
for j in range(len(s)):
if s[j] == alp[i] and contain[i]==-1:
contain[i] = j
print(*contain)
📌 결과
#입력
baekjoon
#출력
1 1 0 0 1 0 0 0 0 1 1 0 0 1 2 0 0 0 0 0 0 0 0 0 0 0
🤔 시행착오.1
s = list(set(input()))
alp = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
contain = [-1 for i in range(len(alp))]
print(s)
for i in range(len(alp)):
for j in range(len(s)):
if s[j] == alp[i]:
contain[i] = j
print(contain)
- set은 순서가 없는 자료구조로 결과 값이 계속 바뀌기 때문에 중복을 제거했지만 알파벳 숫서가 바뀌는 문제가 발생한다.
🤔 시행착오.2
s = list(input())
alp = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
contain = [-1 for i in range(len(alp))]
s = list(dict.fromkeys(s))
for i in range(len(alp)):
for j in range(len(s)):
if s[j] == alp[i]:
contain[i] = j
print(contain)
- dict.fromkeys를 활용하여 중복을 제거했지만 n이 7이 아니라 6으로 바뀜. o 가 한번 있는것으로 count되었기 때문
🔎 다른풀이
str = input()
data = []
for i in range(len(str)):
s = ord(str[i])
data.append(s)
for j in range(97,122+1):
if j in data:
print(data.index(j))
else:
print(-1)
- ord() 함수를 활용하여 문자에 해당하는 유니코드로 바꿔서 문제 푸는 경우
s=input()
answer=[-1]*26
for idx,i in enumerate(s):
if answer[ord(i)-97]==-1:
answer[(ord(i)-97)]=idx
for i in answer:
print(i, end=' ')
- enumerate() 내장함수를 사용하여 인덱스와 값을 동시에 구할 수 있다.
📒 다시보기
백준 [10808.알파벳 개수] | Python
✏️ 문제https://www.acmicpc.net/problem/10808 ✏️ 풀이방법1. 알파벳을 담은 리스트와 0으로 26개가 있는 cnt리스트를 선언한다.2. 단어에 포함된 알파벳이 있을 경우, 해당 알파벳 위치의 순서에 맞춰 cn
somin0416.tistory.com
'Python > online judge' 카테고리의 다른 글
백준 [7785.회사에 있는 사람] | Python (0) | 2024.03.07 |
---|---|
백준 [9093.단어 뒤집기] | Python (0) | 2024.02.16 |
Softeer [level2.전광판] | Python (0) | 2024.02.02 |
백준 [10808.알파벳 개수] | Python (0) | 2024.02.01 |
백준 [1152.단어의 개수] | Python (0) | 2024.01.31 |