Problem Solving with Algorithms

반응형

내용 및 해설 정리: 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

 

 

 

 

반응형
반응형

공유하기

facebook twitter kakaoTalk kakaostory naver band