내용 및 해설 정리: inner-game.tistory.com/46
leetcode.com/problems/reverse-string/
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left, right = left + 1, right - 1
leetcode.com/problems/reverse-integer/
class Solution:
def reverse(self, x: int) -> int:
rev = 0
while x != 0:
pop = x % 10
x //= 10
rev = rev * 10 + pop
return rev
오버플로우처리가 아직도 까다롭네.
-123에 대한 연산 결과.
print(x)
print(x % 10)
print(x//10)
-123
7
-13
파이썬의 음수에 대한 모듈러는 좀 특이하네
class Solution:
def reverse(self, x: int) -> int:
rev = 0
sign = 1
if x < 0: sign = -1
x *= sign
while x != 0:
pop = x % 10
x //= 10
rev = rev * 10 + pop
if rev > 2**31 - 1 or rev < -2**31:
return 0
return rev * sign
leetcode.com/problems/first-unique-character-in-a-string/
카운터 쓰는 법
class Solution:
def firstUniqChar(self, s: str) -> int:
count = collections.Counter(s)
for idx, ch in enumerate(s):
if count[ch] == 1:
return idx
return -1
leetcode.com/problems/valid-anagram/
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
cnt_s = collections.Counter(s)
for c in t:
cnt_s[c] -= 1
if cnt_s[c] < 0:
return False
return True
leetcode.com/problems/valid-palindrome/
class Solution:
def isPalindrome(self, s: str) -> bool:
i, j = 0, len(s)-1
while i < j:
while i < j and not s[i].isalnum():
i += 1
while i < j and not s[j].isalnum():
j -= 1
if i < j and s[i].lower() != s[j].lower():
return False
i += 1
j -= 1
return True
Array - Top Interview Questions[EASY] (1/9) : Java
String - Top Interview Questions[EASY] (2/9) : Java
Linked List - Top Interview Questions[EASY] (3/9) : Java
Trees - Top Interview Questions[EASY] (4/9) : Java
Sorting and Searching - Top Interview Questions[EASY] (5/9) : Java
Dynamic Programming - Top Interview Questions[EASY] (6/9) : Java
Design - Top Interview Questions[EASY] (7/9) - Java
Array - Top Interview Questions[EASY] (1/9) : Python
String - Top Interview Questions[EASY] (2/9) : Python
Linked List - Top Interview Questions[EASY] (3/9) : Python
Trees - Top Interview Questions[EASY] (4/9) : Python
Sorting and Searching - Top Interview Questions[EASY] (5/9) : Python
Dynamic Programming - Top Interview Questions[EASY] (6/9) : Python
Design - Top Interview Questions[EASY] (7/9) - Python