LeetCode 14

[LeetCode/Python]Array and String - Longest Common Prefix

문제 Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". 문자열 배열 중에서 가장 긴 공통 접두사 문자열을 찾아서 반환합니다. 공통 접두사가 없는 경우는 빈 문자열("")을 반환합니다. Input : ["flower", "flow", "flight"] Output : "fl" 이번 문제는 효율성도 생각하지 못할 만큼 문제를 푸는데 급급했던 문제였습니다. 제 코드는 참고만 하시고 다르게 풀어보시는 것을 권유드립니다. 제 코드를 보시려면 더보기를 클릭하시면 됩니다. 더보기 파이썬 코드 class Solut..

[LeetCode/Python]Array and String - Implement strStr()

문제 Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. haystack에서 needle이 처음 발견된 인덱스를 반환하거나 인덱스가 발견되지 않는다면 -1을 반환합니다. Input : haystack = "hello", needle = "ll" Output : 2 이 문제도 저는 알고리즘으로 풀었다기보다 기존 함수를 이용했습니다. 참고만 하시길 바랍니다. 추후에 알고리즘으로 푼다면 추가하도록 하겠습니다. 제 코드를 보시려면 더보기를 클릭하시면 됩니다. 더보기 파이썬 코드 find를 이용하여 간단하게 풀었습니다. class Solution: def strStr(self, ..

[LeetCode/Python]Array and String - Add Binary

문제 Given two binary strings, return their sum (also a binary string). The input strings are both non-empty and contains only characters 1 or 0. 2진수 a와 b를 입력받아서 더한 값을 출력하는 문제입니다. 제 코드는 완벽한 답이 아닙니다. 그래서 이번에는 다른 사람의 풀이도 같이 첨부했습니다. 참고만 하시길 바랍니다. 제 코드를 보시려면 더보기를 클릭하시면 됩니다. 더보기 파이썬 코드 나의 풀이 class Solution: def addBinary(self, a: str, b: str) -> str: return bin(int(a, 2)+int(b, 2))[2:] 다른 사람의 풀이 class ..

[LeetCode/Java]Array and String - Immutable String : Problems & Solutions

나중에 다시 찾아보기 위한 한글 번역 및 요약 Java의 경우 문자열의 중간을 변경하지 못하는 문제와 문자열 추가 시 시간이 오래 걸리는 문제가 있습니다. 이 문제에 대한 해결책입니다. 1. 문자열 수정 작업 문자열을 수정하기 위해서는 문자 배열(char[])을 이용하여 수정할 수 있습니다. public class Main { public static void main(String[] args) { String s = "Hello World"; char[] str = s.toCharArray(); str[5] = ','; System.out.println(str); } } 2. 문자열 추가 작업 public class Main { public static void main(String[] args) { ..

[LeetCode/Java]Array and String - Introduction to String

나중에 다시 찾아보기 위한 한글 번역 및 요약 문자열 소개 문자열은 실제로 유니 코드 문자의 배열입니다. 배열에서 사용한 거의 모든 작업을 수행할 수 있습니다. 그러나 몇 가지 차이점이 있습니다. 문자열을 다룰 때 알아야 할 몇 가지 사항을 살펴보겠습니다. 이러한 기능은 언어마다 많이 다를 수 있습니다. 기능 비교 문자열에는 자체 비교 기능이 있습니다. 하지만 사용하는 언어가 연산자 오버 로딩을 지원하느냐에 따라서 "==" 연산자를 사용하여 비교가 가능하거나 불가능합니다. Java의 경우 연산자 오버 로딩을 지원하지 않기 때문에 "=="를 사용하여 두 문자열을 비교할 수 없습니다. "=="를 사용하면 실제로 이 두 개체가 동일한 개체인지 비교해야 합니다. 코드로 확인해 보시면 이해하시기 편합니다. pub..

[LeetCode/Python]Array and String - Pascal's Triangle

문제 Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. 입력받은 수만큼 파스칼 삼각형의 수들을 배열에 넣어서 출력한다. 파스칼 삼각형 https://ko.wikipedia.org/wiki/%ED%8C%8C%EC%8A%A4%EC%B9%BC%EC%9D%98_%EC%82%BC%EA%B0%81%ED%98%95 파스칼의 삼각형 - 위키백과, 우리 모두의 백과사전 위키백과, 우리 모두의 백과사전. 둘러보기로 가기 검색하러 가기 파스칼의 삼각형(Pascal's triangle)은 수학에서 이항계수를 삼각형 모양의 기하학적 형태로 배열한 것이다. 이것은 블레즈 파스칼� ko.wikipedia.org 예) Input..

[LeetCode/Python]Array and String - Spiral Matrix

문제 Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. 입력받은 배열을 다음과 같이 배열로 만들어서 출력합니다. 코드를 보시려면 더보기를 클릭해 주세요. 더보기 파이썬 코드 class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: tmp = matrix.copy() answer = [] while len(tmp) != 0: answer.extend(tmp[0]) tmp.remove(tmp[0]) tmp = list(map(list, zip(*tmp)))[::-1] return answer ..

[LeetCode/Python/Java]Array and String - Diagonal Traverse

문제 Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image. 2차원 배열을 입력받았을 때 아래와 같은 순서로 배열을 출력한다. 코드를 보시려면 더보기를 클릭해 주세요. 더보기 파이썬 코드 class Solution: def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]: if len(matrix) == 0: return [] N, M = len(matrix), len(matrix[0]) result, inter = [], [] for d in range(N ..

[LeetCode/Python/Java]Array and String - Plus One

문제 Given a non-empty array of digits representing a non-negative integer, increment one to the integer. The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit. You may assume the integer does not contain any leading zero, except the number 0 itself. 이 문제는 입력된 배열을 한 개의 숫자로 인식하여 1로 더한 후의 값을 배열로 출력해야 합니다. 예를 들어서 입..

[LeetCode/Python/Java]Array and String - Largest Number At Least Twice of Others

문제 In a given integer array nums, there is always exactly one largest element. Find whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, otherwise return -1. 배열 안의 최댓값이 다른 모든 값보다 2배 이상일 경우 최댓값의 인덱스를 찾아서 리턴하고 아닐 경우는 -1을 리턴합니다. 예를 들어 배열 A가 [3, 6, 1, 0]일 경우 최댓값 6이 다른 값들보다 2배 이상이기 때문에 1을 리턴합니다. 배열 B가..

728x90