6장 4번
- 나의 풀이
class Solution: def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: wordCount = {} for word in paragraph.lower().split(): word = word.strip(',.') wordCount[word] = wordCount.get(word,0)+1 new = sorted(wordCount.items(),key = lambda x : x[1]) del new[-1] return new[-1][0]
주의:input=['a.']일때는 안됨.
- 답지 풀이
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
words = [word for word in re.sub(r'[^\w]',' ',paragraph)
.lower().split()
if word not in banned]
counts = collections.Counter(words)
return counts.most_common(1)[0][0]
6장 5번
- 나의 풀이
list = [] for str in strs: list = sorted(str) ???
- 답지 풀이
class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: anagrams = collections.defaultdict(list) for word in strs: anagrams[''.join(sorted(word))].append(word) return anagrams.values()
6장 6번
- 답지 풀이
class Solution: def longestPalindrome(self, s: str) -> str: def expand(left:int, right:int) ->str: while left >=0 and right <=len(s) and s[left] == s[right-1]: left -=1 right +=1 return s[left + 1: right -1]
if len(s)<2 or s == s[::-1]:
return s
result = ''
for i in range(len(s)-1):
result = max(result,
expand(i, i+1),
expand(i,i+2),
key = len
)
return result
## 7장 7번
* 답지 풀이
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i] + nums[j] ==target:
return [i,j]
## 7장 8번
left <= right일때 빗물이 고인다.? x
* 답지 풀이
class Solution:
def trap(self, height: List[int]) -> int:
if not height:
return 0
volume = 0
left,right = 0 , len(height) - 1
left_max , right_max = height[left],height[right]
while left<right:
left_max,right_max = max(height[left],left_max),max(height[right],right_max)
if left_max <= right_max:
volume += left_max - height[left]
left +=1
else:
volume += right_max - height[right]
right-=1
return volume
```
'코딩테스트(python)' 카테고리의 다른 글
7장 9번 ~ 12번 (0) | 2021.05.30 |
---|---|
6장 1~3번 문제 (0) | 2021.05.16 |
파이썬 알고리즘 인터뷰 (0) | 2021.05.16 |