728x90 분류 전체보기298 [LeetCode] 202. Happy Number (Python) 1. 문제https://leetcode.com/problems/happy-number/description/?envType=study-plan-v2&envId=top-interview-1502. 풀이Hash 를 사용한 기본 문제. 문제 이해를 완벽하게 못해서 헤맸다.각 자리수를 제곱하여 sum 하는 사이클을 돌다가 만약 1로 끝나면 happy number 이므로 return true 아니면 return falsen=2 인 경우 2 -> 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4 (cycle 발생)즉 방문했던 숫자를 또 방문하면 return false를 반환해야한다. 3. 코드class Solution: def isHappy(self, n: int) -.. 2025. 1. 27. [Nginx] Server Keepalive와 Upstream Keepalive 목차 1. Server Keepalive클라이언트와 nginx 간의 연결HTTP, Server 또는 Location block 내에서 keepalive_timeout, keepalive_requests 설정을 사용클라이언트와 nginx 간의 http 연결을 일정 시간 동안 유지해, 새로운 요청 시 재연결을 방지주요 설정keepalive_timeout클라이언트와 nginx 간의 연결을 유지할 최대 시간기본값: 75skeepalive_requests동일한 연결에서 처리할 최대 요청 수를 제한기본값: 100예시 코드 keepalive_timeout 60s;keepalive_requests 1000; 2. Upstream Keepalivenginx와 백엔드(ex: application server) 간의 연.. 2025. 1. 26. [Nginx] underscore 가 포함된 custom header 확인이 안 될 경우(underscores_in_headers) 목차 1. 개요client request → gateway → nginx → was server 과정으로 요청이 인입되고있습니다.하지만 gateway에서 nginx 로 커스텀 헤더가 인입되지 않는 이슈가 발생하였습니다. 2. nginx 와 underscroes_in_headersnginx 에서 커스텀 헤더가 인입되지 않는 이유와 해결책을 아래와 같습니다.기본적으로 nginx 는 http 헤더의 언더스코어 (_) 를 제거한뒤 springboot server 로 전달합니다.따라서 가급적이면 헤더에 언더스코어를 포함하지 않도록 정의하여 사용합니다.x-custom-header (o)x_custom_header (x)3. 해결방법언더스코어가 포함된 헤더를 사용하기위해서 아래와 같이 nginx.conf 에 설.. 2025. 1. 25. [JAVA] gson에서 Deserialize, Serialize, TypeAdaptor 적용하기 목차 1. 개요test code 작성 중 gson 을 사용하다가 데이터 타입인 Instant를 이해하지 못하여 400 에러가 발생하였습니다.이때 gson이 Instant type을 이해할 수 있도록 직렬화/역직렬화 작업이 필요합니다.먼저 Gson, GsonBuilder에 대해서 알아보겠습니다. 2. Gson이란?java 객체를 json 문법으로 변환해주는 java library 입니다.json 문자를 java 객체로 변환하는 것도 제공합니다.java 객체 → json 문법으로 변환하는 것을 직렬화(serialization)라고 하고json 문법 → java 객체로 변환하는 것을 역직렬화(deserialization)라고 부릅니다. 3. GsonBuilderGson 클래스에는 객체를 json 형식으로 .. 2025. 1. 22. [Springboot] @PreConstruct와 @PreDestory 의미 사용법 목차 1. 스프링 빈의 생명 주기스프링 빈의 생명 주기를 먼저 살펴보면 아래와 같습니다.스프링 컨테이너 생성스프링 빈 생성의존 관계 주입 (DI)초기화 콜백 - 빈이 생성되고 빈의 의존성이 주입된 이후 호출된다. 애플리케이션 동작 및 데이터 사용소멸전 콜백 - 빈이 소멸되기 직전에 호출된다.스프링 종료 2.@PostConstructPostConstruct 어노테이션이란 무엇이며 언제 사용할까요?객체를 초기화 할 때 수행한다.객체가 생성된 후 별도의 초기화 작업을 위해 실행하는 메소드를 선언하여 사용한다.@PostConstruct 어노테이션을 설정해놓은 init 메소드는 WAS 가 띄워질 때 실행된다.@PostConstructpublic void init() { System.out.println("초기.. 2025. 1. 19. [HackerRank] Contacts (Python) 1.문제https://www.hackerrank.com/challenges/contacts/problem 2.풀이처음에 정직하게 구현으로 풀다가 time limit exceeded 나서 실패..단순해 보이지만 Time Complexity를 신경써서 풀어야하는 문제이다.def contacts(queries): answer = [] arr = [] for i in range(len(queries)): command = queries[i][0] if command == 'add': data = queries[i][1] arr.append(data) else: target = queries[i][1].. 2025. 1. 18. [HackerRank] Find the Running Median (Python) 1. 문제https://www.hackerrank.com/challenges/find-the-running-median/problem 2. 풀이처음엔 a의 길이가 홀수, 짝수 케이스로 나누어서 단순히 중위값을 구하려고했다.참고로 python에서 n / 2 를 하면 실수를 반환하지만 n//2를 하면 int 정수를 반환한다.def runningMedian(a): answer = [] for i in range(1, len(a)+1): li = sorted(a[:i]) n = len(li) # odd if (n % 2 != 0): median = li[n // 2] else: med.. 2025. 1. 18. [HackerRank] Tree: Level Order Traversal 1. 문제https://www.hackerrank.com/challenges/tree-level-order-traversal/problem 2. 풀이처음에 preOrder 문제로 잘 못 생각한 문제. 레벨을 기준으로 순회를 해야한다.아래 코드는 preOrder 코드def levelOrder(root): if root is None: return print(root.info) levelOrder(root.left) levelOrder(root.right) 레벨 기준으로 순회하려면 BFS 와 같이 queue를 사용해야한다.다른 사람 풀이를 보니 stack 과 queue 의 장점을 모두 가지고 있는 deque를 사용해서 deque 를 사용해서 해결한다. queue 의 inse.. 2025. 1. 18. [HackerRank] Tree: Height of a Binary Tree (Python) 1. 문제https://www.hackerrank.com/challenges/tree-height-of-a-binary-tree/problem 2. 풀이Binary의 가장 높은 height를 구하는 문제.현재 root node 가 None이면 -1 반환재귀함수를 이용해서 왼쪽노드와 오른쪽 노드의 height 구한다. 시간 복잡도 : O(N) - 모든 노드를 한번씩 방문하므로 시간 복잡도는 N, N은 여기서 노드 수공간 복잡도 : O(H) - 재귀호출 스택의 공간 복잡도는 트리의 높이 H 와 동일 3. 코드def height(root): if root is None: return -1 depth_left = height(root.left) depth_right = height.. 2025. 1. 18. [HackerRank] Balanced Brackets (Python) 1. 문제https://www.hackerrank.com/challenges/balanced-brackets/problem 2.풀이stack을 이용한 기본 문제 3.코드def isBalanced(s): st = [] print(s) for i in range(len(s)): if (s[i] == "(" or s[i] == "{" or s[i] == "["): st.append(s[i]) elif s[i] == ")": if (len(st) 0): return "NO" return "YES" 4.리팩토링dictionary 사용해서 중복된 코드 제거하기def isBalanced(s): stack = [].. 2025. 1. 18. [Kotlin] List와 MutableList 개념 및 차이점 val countryList = listOf("한국","미국","일본")val minusCountryList = countryList - "일본" // "한국", "일본" 값의 Listval plusCountryList = countryList + "중국" // "한국","미국","일본","중국" 값의 List val newlistData = listOf(1, 2, 3)val plusList = listOf(4, 5, 6)newlistData.addAll(plusList) // List 합치기val newlistData2 = plusList1 + plusList2 // + 기호로 합치기val newListData3 = plusList1.plus(plusList2) // plus함수로 합치기val newL.. 2025. 1. 18. [Spring] 스프링에서 특정 HTTP 응답코드 반환하기 (ResponseEntity, @ResponseStatus) 목차 1. Spring 에서 HTTP 응답상태 코드Spring은 HTTP 응답 상태 코드를 사용자 정의 할 수 있는 다음과 같은 방법을 제공합니다.ResponseEntity 객체 응답@ResponseStatus 어노테이션ResponseStatusException 예외 발생 2. ResponseEntityResponseEntity 인스턴스와 함께 HTTP 응답 상태 코드를 전송할 수 있습니다.예시 코드요청을 통해서 전달 받은 Student 인스턴스를 생성하는 API가 있고, API를 호출했을 때 성공적으로 수행했을 때 Spring에서는 200 응답 코드를 보냅니다.요청을 통해서 전달 받은 Student 인스턴스를 생성하는 API에서 성공적으로 처리가 완료되면 201(CREATED) 응답을 보내고 싶을 .. 2025. 1. 17. [Kotlin] @NotNull Validation 사용하기 목차 1. Gradle 설정spring-boot-starter-validation 의존성을 명시해야 valid 사용이 가능합니다.implementation 'org.springframework.boot:spring-boot-starter-validation' 2. Valid 사용방법data class ValidRequestDto( @field:NotNull(message = "value는 필수 입력값입니다.") val value: String? = null, @field:NotNull(message = "createdAt은 필수 입력값입니다.") val createdAt: LocalDate? = null, @field:NotNull(message = "number는 .. 2025. 1. 16. [LeetCode] Valid Parentheses (Python) 1.Quiz2.Solution전형적인 stack 문제. 코드를 깔끔하게 짜도록 연구해야겠다.다른 사람 코드를 보니 괄호를 미리 정의해두고 닫힘 괄호가 나타나면 stack의 마지막 값을 dict 를 사용하여 짝이 있는지 확인하도록했다.class Solution: def isValid(self, s: str) -> bool: parentheses = {"}":"{", "]":"[", ")":"("} stack = [] for char in s: if char in parentheses.keys(): if len(stack) and stack[-1] == parentheses[char]: stack.pop().. 2025. 1. 15. [LeetCode] RansomNote (Python) 1.Quizhttps://leetcode.com/problems/ransom-note/description/?envType=study-plan-v2&envId=top-interview-150 2.Solutionmagzine 구성 문자로 reansomNote 문자를 만들 수 있는지 true / false 반환하는 문제다른 사람 풀이를 보니 set 을 사용해서 count 개수로 비교하여 ransomNote 가 magazine 보다 많으면 false 를 반환하도록 했다.class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: for char in set(ransomNote): if ra.. 2025. 1. 15. [LeetCode] Find the Index of the First Occurrence in a String (Python) 1.문제https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/description/?envType=study-plan-v2&envId=top-interview-150 2.풀이더 짧은 길이인 needle 문자열이 haystack 에 포함되어있는지 체크이중포문을 돌지않는게 포인트!다른 사람 코드를 보니 index 를 찾는 python method 가 있었다.class Solution: def strStr(self, haystack: str, needle: str) -> int: if needle in haystack: index1 = haystack.index(needle) .. 2025. 1. 15. [LeetCode] 14.Longest Common Prefix (Python) 1.문제https://leetcode.com/problems/longest-common-prefix/?envType=study-plan-v2&envId=top-interview-1502.풀이1) 주어진 리스트의 원소를 길이순으로 정렬한다.2) 가장 짧은 단어를 기준으로 순환하여 비교한다.3) 반복문을 돌면서 해당 index 의 단어와 첫번째 단어의 index 가 동일한지 체크하고 동일하지 않다면 그 부분까지 substring 해서 반환한다. 3.코드class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: if (len(strs) == 0): return "" if (len(str.. 2025. 1. 15. [LeetCode] Length of Last Word (Python) 1.문제https://leetcode.com/problems/length-of-last-word/description/?envType=study-plan-v2&envId=top-interview-150 2.풀이공백을 기준으로 split 메소드를 사용하면 간단한 문제! 3.코드class Solution: def lengthOfLastWord(self, s: str) -> int: last_word = s.split()[-1] # print(last_word) return len(last_word) 2025. 1. 15. [LeetCode] Roman to Integer 1.문제https://leetcode.com/problems/roman-to-integer2.풀이dictionary를 이용하여 푸는 문제. 모든 경우의 수를 조합하여 미리 dict 를 만들어도 되고, 주어진 문자열에 대한 값만 dict 로 만들어도된다.[다른사람 풀이]class Solution: def romanToInt(self, s: str) -> int: roman = { "I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000 } res = 0 for i in range(len(s)): if i + 1 3.코드class Sol.. 2025. 1. 14. Kotlin 예외처리(2) - check(), checkNotNull() 목차 1. check()check()매개변수의 값이 참인지 체크거짓이라면 throwIllegalStateException 예외를 반환합니다.*IllegalStateException-일반적으로 IllegalStateException은 메소드를 호출할 상태(State)가 아닐 때 발생시키는 exception이다. 예시코드fun connect(isConnected: Boolean) { //적용 전 if (isConnected) { throw IllegalStateException("이미 연결되어있습니다.") } //적용 후 check(!isConnected) {"이미 연결되어있습니다."}} 2. checkNotNull()checkotNull()매개변수의 값이 n.. 2025. 1. 13. 이전 1 2 3 4 5 6 ··· 15 다음 728x90