정수를 담은 배열과 목표 값이 주어질 때 더해서 목표값이 되는 index를 리턴하는 문제 (중복x)
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hash = {}
for i, v in enumerate(nums):
n = target - v
if n in hash:
return [hash[n], i]
hash[v] = i
return list()
-2^31 <= integer <= 2^31-1
class Solution:
def reverse(self, x: int) -> int:
flag = False
if x < 0:
flag = True
x *= -1
res = 0
while x > 0:
res = res*10 + x%10
x //= 10
if flag:
res *= -1
if -2**31 > res or res > 2**31-1:
return 0
return res
정수가 회문 문자열인지 체크 ( 음수 포함 )
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
else:
a = list()
while x > 0:
a.append(x%10)
x //= 10
for i in range(len(a) // 2):
if a[i] != a[-1-i]:
return False
return True
로마숫자 -> 정수로 변환
class Solution:
def romanToInt(self, s: str) -> int:
stack = list(str)
res = 0
while stack:
s = stack.pop()
if s == 'M':
if stack[-1] == 'C':
stack.pop()
res += 900
else:
res += 1000
elif s == 'D':
if stack[-1] == 'C':
stack.pop()
res += 400
else:
res += 500
elif s == 'C':
if stack[-1] == 'X':
stack.pop()
res += 90
else:
res += 100
elif s == 'L':
if stack[-1] == 'X':
stack.pop()
res += 40
else:
res += 50
elif s == 'X':
if stack[-1] == 'I':
stack.pop()
res += 9
else:
res += 10
elif s == 'V':
if stack[-1] == 'I':
stack.pop()
res += 4
else:
res += 5
else:
res += 1
return res
example Input: ['abc', 'abcd', 'ab']
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if len(strs) == 0:
return ""
minLength = 2147000000
for v in strs:
if len(v) < minLength:
minLength = len(v)
s = 0
e = minLength
res = 0
while s <= e:
mid = (s+e) // 2
if all([strs[0][:mid] == strs[k][:mid] for k in range(1, len(strs))]):
res = mid
s = mid + 1
else:
e = mid - 1
return strs[0][:res]