나는 스택을 이용해 문제를 풀었다.
빈 스택으로 시작해서 하나씩 늘려주다가 word
와 일치하는 순간 해당 answer
를 반환했다.
내가 찾은 규칙은 다음과 같았다.
U
라면 U
모두 + 바로 전까지 빼고 다음 알파벳 삽입예시 ) AUUUO
1번 규칙 적용, AUUUO
-> AUUUU
2번 규칙 적용, AUUUU
-> AUUU
-> AUU
-> AU
-> A
-> [ ] -> E
def solution(word):
answer = 0
stack = []
alp = ['A', 'E', 'I', 'O', 'U']
while word != ''.join(stack):
if len(stack) != 5:
stack.append(alp[0])
else:
l = stack.pop()
while l == alp[-1]:
l = stack.pop()
stack.append(alp[alp.index(l) + 1])
answer += 1
return answer
굳이 리스트를 생성하지 않고 문자열 사용해도 됐었다.
def solution(word):
answer = 0
stack = []
while word != ''.join(stack):
if len(stack) != 5:
stack.append('A')
else:
p = stack.pop()
while p == 'U':
p = stack.pop()
stack.append("AEIOU"["AEIOU".index(p) + 1])
answer += 1
return answer
from itertools import product
solution = lambda word: sorted(["".join(c) for i in range(5) for c in product("AEIOU", repeat=i+1)]).index(word) + 1
문자열의 길이가 길지 않으니 product
로 모든 경우의 수 탐색. 문자열도 sort
가 된다.
한 문장 구현 멋지다.
def solution(word):
answer = 0
for i, n in enumerate(word):
answer += (5 ** (5 - i) - 1) / (5 - 1) * "AEIOU".index(n) + 1
return answer
이건 규칙을 이용한 풀이.
permutations
from itertools import permutations
combinations
from itertools import combinations
product
from itertools import product
combinations_with_replacement
from itertools import combinations_with_replacement