[BOJ] 2941 크로아티아 알파벳

[BOJ] 2941 크로아티아 알파벳

문제 링크

열심히 조건문을 작성해서 풀이했다. 물론 풀이하면서 느꼈지만.. 그렇게 푸는 거 아닌 것 같았다. 하지만 replace()함수를 몰랐던 나는 그럴 수 밖에 없었다. 이렇게 부끄러운 풀이를 굳이 블로그에 남기는 이유는 나중에 다시 봤을 때 내 생각이 여기에 갇혀 있었음을 나중에라도 느끼기 위함이다.

replace() replace 함수는 무려 문자열 안에서 특정 문자를 새로운 문자로 변경하는 기능을 수행한다. replace(old, new, [count]) 의 구조를 가지며 count는 변경할 횟수이다. 빈 값으로 두면 문자열의 전체에서 old에 해당하는 부분을 모두 new로 변경한다.

나의 풀이 - 시간초과

words = input()

count = 0

for i in range(len(words)):
  if(words[i] == 'j'):
    if(i>=1):
      if(words[i-1] == 'l' or words[i-1] == 'n'):
        continue
      else:
        count+=1
    else:
      count+=1
  elif(words[i] == '='):
    if(i>=1):
      if(words[i-1] == 'c' or words[i-1] == 's' or words[i-1] == 'z'):
        continue
      else:
        count+=1
    elif(i==0):
      continue
    else:
      count+=1
  elif(words[i] == '-'):
    if(i>=1):
      if(words[i-1] == 'c' or words[i-1] == 'd'):
        continue        
      else:
        count+=1
    elif(i==0):
      continue
    else:
      count+=1
  elif(words[i] == 'z'):
    if(i>=1 and len(words)-i-1>=1):
      if(words[i-1]=='d' and words[i+1] == '='):
        continue
      else:
        count+=1
    else:
      count+=1
  else:
    count+=1

print(count)

다른 풀이 - replace 적용

croatia = ['c=', 'c-', 'dz=', 'd-', 'lj', 'nj', 's=', 'z=']
word = input()

for i in croatia :
    word = word.replace(i, '*')
print(len(word))

© 2021. All rights reserved.