틀린 코드
원인: 딕셔너리와 리스트 만드는 것을 한번에 하려고 하면서 cnt가 제대로 더해지지 않았음
중간에 문자가 하나만 존재할 경우 cnt가 하나가 더해지지 않기 때문에 return 하면서 result 카운팅이 이루어지지 않음
반례 :
input:
2
ccazzzzbb
abbbc
output:
0
answer:
2
def check_word(word):
global result
dicts = {}
cnt = 0
for i in range(len(word)):
if dicts.get(word[i]): # 딕셔너리 값이 있따면
dicts[word[i]] += 1
else: # 값이 없다면
dicts[word[i]] = 1
# 전 인덱스와 비교해서 다를 때
if i > 0 and word[i] != word[i-1]:
# 현재 개수가 cnt와 다르다면 cnt = 1 로 만든다
if cnt != dicts.get(word[i-1]): return
cnt = 0
else:
cnt += 1
result += 1
정답코드
# 1316 그룹 단어 체커 실버5
'''
한개짜리 단어도 ok
같은 문자열이 이어져야된다
'''
def check_word(word):
global result
dicts = {}
cnt = 0
for i in range(len(word)):
if dicts.get(word[i]): # 딕셔너리 값이 있따면
dicts[word[i]] += 1
else: # 값이 없다면
dicts[word[i]] = 1
for j in range(len(word)-1):
# 전 인덱스와 비교해서 다를 때
if word[j] != word[j+1]:
# 현재 개수가 cnt와 다르다면 cnt = 1 로 만든다
if cnt+1 != dicts.get(word[j]): return
cnt = 0
else:
cnt += 1
print(dicts)
result += 1
n = int(input())
result = 0
for _ in range(n):
word = input()
check_word(word)
print(result)
'알고리즘 문제풀이' 카테고리의 다른 글
백준 15649. N과 M (1) Python 백트래킹 실버3 (0) | 2024.03.20 |
---|---|
백준 2941 크로아티아 알파벳 Python 구현 문자열실버5 (0) | 2024.03.19 |
백준 1049 기타줄 Python 수학 그리디 실버4 (0) | 2024.03.18 |
백준 1026 보물 Python 수학 그리디 정렬 실버4 (0) | 2024.03.18 |
백준 1476 날짜계산 Python 수학 브루트포스실버5 (1) | 2024.03.17 |