본문 바로가기

string4

Valid Parentheses Valid Parentheses 문자열의 유효성 검사하기 Solution class Solution: def isValid(self, s: str) -> bool: stack = [] for c in s: if c in '([{': stack.append(c) elif not stack : return False else: o = stack.pop() if o == '[' and c == ']': continue if o == '(' and c ==')' : continue if o == '{' and c == '}' : continue return False return not stack 2022. 7. 10.
[leetcode] Group Anagrams Anagram A word or phrase formed by rearranging the letters of a different word or phrase Group Anagrams 문자열 array가 주어질때 anagram 끼리 그루핑 Solution 문자열을 구성하는 문자를 정렬한 결과가 같으면 같은 Group 으로 from collections import defaultdict class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: groups = defaultdict(list) for word in strs: groups[''.join(sorted(word))].append(word) return .. 2022. 4. 19.
[leetcode] most common word Most Common Word paragraph와 금지 단어 배열 banned 가 주어질때 banned에 속하지 않은 단어중아 가장 많이 나온 단어를 리턴 최소 하나의 단어는 banned 에 속하지 않음을 보장 문자열의 대소문자 구분은 없고 리턴값은 소문자로 이루어진 단어 Solution 1. paragraph를 단어 리스트로 만들기 쉼표, 마침표 등의 문자는 제거 모든 문자를 소문자로 바꾸고 공백 문자를 기준으로 단어로 나누기 2. 단어별 개수 Counter로 카운팅 banned에 포함된 단어는 버리기 Code import re from collections import Counter class Solution: def mostCommonWord(self, paragraph: str, banned: L.. 2022. 4. 19.
[leetcode] valid palindrome palindrome 앞으로 읽어도 뒤로 읽어도 동일 valid palindrome 대소문자를 구분하지 않고, Alphanumeric 아닌 문자는 제외 주어진 phrase 가 palindrome 인지 여부를 bool 로 리턴 대문자 소문자 변환 s = s.upper() # 대문자 변환 문자열 반환 s = s.lower() # 소문자 변환 문자열 반환 Alphanumeric만 추출하기 s = ''.join( c for c in s if c.isalnum()) # 정규표현식 import re s = re.sub('\W','',s) # 문자열에서 \W(문자나 숫자가 아닌것)를 찾아서 제거한 문자열 반환 Solution start, end 두개의 index 를 이용 각각 앞, 뒤에서 Alphanumeric인 문자.. 2022. 2. 16.