알고리즘 풀이
문자열 내 마음대로 정렬하기 (출처 : 프로그래머스)
🧚
문자열의 접근할 특정 인덱스의 글자를 기준으로
정렬된 문자열의 배열을 출력하는 문제이다.
즉, 특정 인덱스의 글자와 함께 문자열은 같이 움직여야 한다.
단, 조건은 특정 인덱스의 글자가 겹치는 경우가 존재하는데 그 경우에는 문자열의 정렬 기준에 따른다는 것이다.
First Attempt
처음에는 딕셔너리로 접근했다.
단, key-value 값 설정에서 특정 인덱스의 글자가 겹치는 경우를 생각해야 하기 때문에
key에는 문자열을,
value에는 특정 인덱스의 글자를 두고
찝찝해서 다른 사람의 풀이는 어떤가 살펴보았다.
그 중에서도 인덱스 글자를 머리글처럼 붙여서 굳이 딕셔너리를 사용하지 않고 시간 복잡도를 줄이고 코드도 훨씬 간단해지는 풀이를 발견했다.
로직또한 간단했다.
📌
# 배열 풀이
def solution(strings, n):
answer = []
sorted_solo = []
for string in strings:
sorted_solo.append(string[n])
sorted_solo = sorted(sorted_solo)
sorted_string = sorted(strings)
# print(sorted_solo)
for sorted_solo in sorted_solo:
for one in sorted_string:
if one[n] == sorted_solo:
answer.append(one)
sorted_string.remove(one)
break
return answer
# 딕셔너리 풀이
def solution(strings, n):
alpha_dict = {}
for string in strings:
alpha_dict[string] = string[n]
sorted_values = sorted(alpha_dict.values())
sorted_keys = sorted(alpha_dict.keys())
for value in sorted_values:
for key in sorted_keys:
if value == alpha_dict[key]:
answer.append(key)
sorted_keys.remove(key)
break
return answer
# Better Solution
def solution(strings, n):
answer = []
for string in strings:
answer.append(string[n] + string)
answer.sort()
for i in range(len(answer)):
answer[i] = answer[i][1:]
return answer
붕대감기 (출처 : 프로그래머스)
🧚
문제의 길이가 꽤나 길어 어제 푼 카카오 인턴 문제와 비슷하게 해석하는데 꽤나 오래 걸렸다.
책을 읽어야 하나
무튼
조건을 정리해보겠다.
회복 로직
공격 받는 로직
구현 로직
📌
def solution(bandage, health, attacks):
answer = []
max_health = health
health_time = bandage[0]
sec_health = bandage[1]
plus_health = bandage[2]
attack_dict = {}
for attack in attacks:
attack_dict[attack[0]] = attack[1]
l = attacks[-1][0]
stck = 0
is_attacked = False
answer.append(health)
for i in range(1, l+1):
if i in attack_dict.keys():
is_attacked = True
if (health - attack_dict[i] <= 0):
return -1
health -= attack_dict[i]
stck = 0
else:
is_attacked = True
if health >= max_health:
stck += 1
continue
elif (stck+1) >= health_time:
if (health + (sec_health + plus_health) >= max_health):
health = max_health
else:
health += (sec_health + plus_health)
stck = 0
else:
if (health + sec_health >= max_health):
health = max_health
else:
health += sec_health
stck += 1
if health <= 0:
return -1
return health
마주했던 ERROR
Object of type set is not JSON serializable
: LIST 타입을 원하는 자리에 SET 상태의 컬렉션을 넣고자 할 때 나타나는 오류
-> 해결 : LIST로 SET 상태의 컬렉션을 다시 감싸야 한다.