유효한 팰린드롬
- 입력 1 : s = "A man, a plan, a canal: Panama"
- 출력 1 : true
- 입력 2 : s = "race a car"
- 출력 2 : false
풀이 1) 슬라이싱 기법
class Solution:
def isPalindrome(self, s: str) -> bool:
strs = [char.lower() for char in s if char.isalnum()]
return strs == strs[::-1]
solution = Solution()
test_case: str = "A man, a plan, a canal: Panama"
result: bool = solution.isPalindrome(test_case)
print(result)
풀이 2) 리스트를 이용한 큐, 스택 사용
class Solution:
def isPalindrome(self, s: str) -> bool:
strs: List[str] = [char.lower() for char in s if char.isalnum()]
while(len(strs) > 1):
if strs.pop() != strs.pop(0):
return False
return True
solution = Solution()
test_case: str = "A man, a plan, a canal: Panama"
result: bool = solution.isPalindrome(test_case)
print(result)
풀이 3) Deque 사용
class Solution:
def isPalindrome(self, s: str) -> bool:
strs: Deque = collections.deque()
for char in s:
if char.isalnum():
strs.append(char.lower())
while len(strs) > 1:
if strs.pop() != strs.popleft():
return False
return True
solution = Solution()
test_case: str = "A man, a plan, a canal: Panama"
result: bool = solution.isPalindrome(test_case)
print(result)
문자열 뒤집기
- 입력 1 : s = ["H", "e", "l", "l", "o"]
- 출력 1 : ["o", "l", "l", "o", "h"]
- 입력 2 : s = ["H", "a", "n", "n", "a", "h"]
- 출력 2 : ["h", "a", "n", "n", "a", "H"]
풀이 1) 스왑
class Solution:
def reverseString(self, s: List[str]) -> None:
for i in range(len(s) // 2):
s[i], s[len(s) - 1 - i] = s[len(s) - 1 - i], s[i]
풀이 2) 투포인터 기반 스왑
class Solution:
def reverseString(self, s: List[str]) -> None:
left, right = 0, len(s) - 1
while (left < right):
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
풀이 3) 리스트 내장 함수
class Solution:
def reverseString(self, s: List[str]) -> None:
s.reverse()
풀이 4) 슬라이싱
class Solution:
def reverseString(self, s: List[str]) -> None:
s[:] = s[::-1]
로그 파일 재정렬
- 입력 : logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"]
- 출력 : ["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"]
풀이 1) 기본적인 풀이
class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
letters, digits = [], []
for log in logs:
if log.split()[1].isdigit():
digits.append(log)
else:
letters.append(log)
letters.sort(key=lambda id: (id.split()[1:], id.split()[0]))
return letters + digits
가장 흔한 단어
- 입력 :
- paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
- banned = ["hit"]
- 출력 : "ball"
풀이 1) 기본적인 풀이
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
words: List[str] = [word for word in re.sub(r'[^\w]', ' ', paragraph).lower().split() if word not in banned]
counter_dict: Counter = collections.Counter(words)
return counter_dict.most_common(1)[0][0]
solution = Solution()
paragraph: str= "Bob hit a ball, the hit BALL flew far after it was hit."
banned: List[str] = ["hit"]
result: List[str] = solution.mostCommonWord(paragraph, banned)
print(result)
그룹 애너그램
- 입력 : strs = ["eat","tea","tan","ate","nat","bat"]
- 출력 : [["bat"], ["nat","tan"], ["ate","eat","tea"]]
풀이 1) 애너그램 특성 이용 + 딕셔너리
- 실행 속도 : 96 ms
- 애너그램은 정렬할 경우 모두 같은 값을 가지는 특성이 있습니다. 따라서 단어를 모두 정렬한 후 그 단어를 키로 사용하여 그룹핑하는 방식입니다.
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
anagrams: dict = collections.defaultdict(list)
for word in strs:
anagrams[''.join(sorted(word))].append(word)
return list(anagrams.values())