본문 바로가기

Algorithm39

[알고리즘] 알파벳 찾기 백준 10809 (Python) 알파벳 개수 찾는 문제와 거의 동일하다. 리스트를 -1로 초기화하고 해당 알파벳의 인덱스에 입력받은 알파벳의 인덱스 값을 넣어주면 된다. 코드 import sys alphabet =[-1] * 26 str = sys.stdin.readline().rstrip() for i in range(len(str)): if(alphabet[ord(str[i]) - 97] == -1 ): alphabet[ord(str[i]) - 97] = i print(*alphabet) 입출력 2022. 1. 17.
[알고리즘] 알파벳 개수 백준 10808 (Python) 알파벳 하자마자 아스키 코드가 생각났다. 파이썬에선 아스키코드 값을 반환하는 내장함수 ord()가 존재한다. 틀린 코드 import sys alphabet =[0] * 26 str = sys.stdin.readline() for i in str: alphabet[ord(i) - 97] += 1 print(*alphabet) 입출력 문자열을 입력받을 때 sys.stdin.realine().rstrip()으로 바꿔주니 문제가 해결됐다. 코드 import sys alphabet =[0] * 26 str = sys.stdin.readline().rstrip() for i in str: alphabet[ord(i) - 97] += 1 print(*alphabet) 입출력 아 그리고 처음엔 리스트를 공백으로 구분하.. 2022. 1. 17.
[알고리즘] 덱 백준 10866 (Python) 큐와 비슷하지만 덱은 양쪽에서 push, pop이 가능하다. 코드 import sys n = int(input()) deque = [] for i in range(n): command = sys.stdin.readline().split() if command[0] == 'push_front' : deque.insert(0,command[1]) elif command[0] == 'push_back' : deque.append(command[1]) elif command[0] == "pop_front" : if len(deque) == 0 : print(-1) else : print(deque.pop(0)) elif command[0] == "pop_back" : if len(deque) == 0 : pri.. 2022. 1. 16.
[알고리즘] 큐 백준 10845 (Python) queue 는 선입선출이라는 것을 기억하고 풀었다. 코드 import sys n = int(sys.stdin.readline()) queue = [] for i in range(n): command = sys.stdin.readline().split() if command[0] == 'push' : queue.insert(0,command[1]) elif command[0] == 'pop' : if len(queue) == 0: print(-1) else : print(queue.pop()) elif command[0] == 'size' : print(len(queue)) elif command[0] == 'empty' : if len(queue) == 0 : print(1) else : print(0).. 2022. 1. 14.
[알고리즘] 괄호 백준 9012 (Python) Stack을 pop 했을 때 top의 값이 감소하는 것을 이용하여 풀었습니다. 코드 import sys n = int(sys.stdin.readline()) for i in range(n) : stack = sys.stdin.readline() top = 0 for j in stack: if j == '(' : top += 1 elif j == ')' : top -= 1 if top 0 : print('NO') elif top == 0: print('YES') 입출력 2022. 1. 14.
[알고리즘] 스택 백준 10828 (Python) 코드 import sys n = int(sys.stdin.readline()) stack = [] for i in range(n): command = sys.stdin.readline().split() if command[0] == 'push': stack.append(command[1]) elif command[0] == 'pop': if len(stack) == 0: print(-1) else: print(stack.pop()) elif command[0] == 'size': print(len(stack)) elif command[0] == 'empty': if(len(stack)==0): print(1) else : print(0) elif command[0] == 'top': if len(stac.. 2022. 1. 14.