반응형

https://leetcode.com/problems/reverse-string/

  1. 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 +=1
            right -=1

https://leetcode.com/problems/reorder-data-in-log-files/

  1. Reorder Data in Log Files
class Solution:
    def reorderLogFiles(self, logs: List[str]) -> List[str]:
        '''
        로그의 가장 앞 부분은 식별자
        문자로 구성된 로그가 숫자 로그보다 앞에 온다.
        식별자는 순서에 영향을 끼치지 않지만, 문자가 동일할 경우 식별자 순으로 한다.
        숫자로그는 입력 순서대로 한다.
        => 1. 숫자보다 문자 로그 먼저
        => 2. 문자 동일할 경우 식별자 순(식별자는 로그 가장 앞)
        '''

        letters, digits=[], []


        for log in logs:
            #로그가 숫자라면 (log.split()는 string을 반환)
            if log.split()[1].isdigit():
                digits.append(log)

            #로그가 문자라면
            else:
                letters.append(log)
        #문자일 경우 로그기준으로 정렬, 식별자를 뒤로, 문자 동일할 경우 식별자 순으로 정렬   
        letters.sort(key=lambda x: (x.split()[1:], x.split()[0]))

        #문자+숫자
        return letters+digits

https://leetcode.com/problems/most-common-word/

\19. Most Common Word

'''
금지된 단어를 제외한 가장 흔하게 등장하는 단어를 출력하라
대소문자를 구분하지 않으며, 구두점(마침표, 쉼표) 또한 무시한다.

Input: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"]
Output: "ball"

1. 데이터 처리 => 대소문자 없애고, 구두점 없앰
2. 빈도수 체크
'''

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:

        #cleaning
        #\w은 단어문자를 뜻하며 ^은 not을 의미한다.
        #문자열 앞에 r이 붙으면 해당 문자열이 구성된 그대로 문자열로 반환
        #즉 문자가 아닌 모든 문자를 공백으로 치환한다.
        #re.sub('패턴', '바꿀문자열', '문자열', 바꿀횟수)
        #words에는 cleaning된 word가 순차적으로 들어가게됨
        '''
        # 리스트 안에서 for 문 사용하기 1
        list = [ num * 3 for num in list ]
        '''

        #\w, 즉 단어 문자가 아니면 공백으로 치환하고 lower, split함
        words =[word for word in re.sub(r'[^\w]',' ', paragraph).lower().split()
            if word not in banned] #금지된 단어에 당되는 경우엔 포함X


        #개수 세기
        #딕셔너리 사용하여 횟수 셈
        #int형 딕셔너리 생성
        counts = collections.defaultdict(int)
        for word in words:
            counts[word] += 1 #해당되는 word 수 셈

        #딕셔너리 변수 counts에서 값이 가장 큰 키를 가져옴
        #max함수에 key를 지정하여 argmax를 간접적으로 추출
        '''
        >>> a = {'name':'pey', 'phone':'0119993323', 'birth': '1118'}
        >>> a.get('name')
        'pey'
        '''

        return max(counts, key=counts.get)

        #most_common(1)사용 가능 => 최빈값 1개 반환(리스트에 담긴 튜플 형태로
        '''
        counts=collections.Counter(words)
        return counts.most_common(1)[0][0] #=> [('ball', 2)]이므로
        '''

https://leetcode.com/problems/group-anagrams/submissions/

'''
애너그램 = 재배열하여 다른 뜻을 가진 단어로 바꾸는것

Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

방법
1. strs의 단어들을 정렬하여 같은지 비교



'''


class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        #딕셔너리 생성
        anagrams = collections.defaultdict(list)

        for word in strs:
            #정렬하여 key, value딕셔너리에 삽입
            #list에서 문자열로 변환 -> 리스트(List)를 특정 구분자를 포함해 문자열(String)으로 변환
            anagrams[''.join(sorted(word))].append(word)

        #values() -> 모든 value들을 출력
        return list(anagrams.values())

https://leetcode.com/problems/longest-palindromic-substring/

'''
가장 긴 펠린드롬 부분 문자열을 출력

Input: s = "babad"
Output: "bab"

방법
1. 처음, 끝 비교 => 안맞으면 끝에서 2번째부터 계속 비교
(대칭되게 비교해야함 => aa, aaa, aaaa, aaaaa)
(1)b - d (x)
(2)b - a (x)
(3)b - b (O)
(4)길이가 3이므로 비교  X => 끝

(1)a - d
(2)a - a
.
.
.

2. 홀수칸, 짝수칸을 처음부터 이동 => 대칭되면 확장
더 효율적
'''



class Solution:
    def longestPalindrome(self, s: str) -> str:

        #s[left]==s[right]일 경우 범위 늘려가며 비교
        def expand(left:int, right:int)->str:
            while left >=0 and right < len(s) and s[left]==s[right]:
                left -= 1
                right += 1
            #left -= 1 했으므로 left+1, list범위는 right-1까지이므로 right
            return s[left+1:right]

        '''
        Input: s = "ac"
        Output: "a"
        '''
        #s가 짧거나 s자체가 펠린드롬일 경우 처리
        if len(s) < 2 or s==s[::-1]:
            return s


        #펠린드롬이 없는 경우
        result = ''

        for i in range(len(s) - 1):
            #max기준 len
            #홀수인 경우, 짝수인 경우
            result = max(result, expand(i, i+1), expand(i, i+2), key=len)

        return result
728x90
반응형

'공부 > 파이썬 알고리즘' 카테고리의 다른 글

스택과 큐  (0) 2021.10.14
연결리스트  (0) 2021.09.15
배열  (0) 2021.09.15
etc  (0) 2021.07.01
파이썬 문법  (0) 2021.06.28
블로그 이미지

아상관없어

,