본문 바로가기

알고리즘 문제풀이

백준 1316 그룹 단어 체커 Python 정렬 문자열 실버5

틀린 코드

원인:  딕셔너리와 리스트 만드는 것을 한번에 하려고 하면서 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)