Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
Tags
- WAS웹서버
- 스프링이미지업로드
- 스프링익셉션처리
- ssh도커설치
- 출처 메타코딩
- centos도커설치
- vm도커설치하는법
- springboot_exception_handler
- 출처 문어박사
- 파이썬sort
- 스프링부트중복예외처리
- 스프링사진업로드
- 스프링부트사진올리기
- 스프링부트팔로잉
- 출처 코딩셰프
- 도커설치하는법
- 스프링부트구독취소
- 스프링부트서버에사진전송
- 스프링구독
- 스프링부트팔로우취소
- 인스타클론
- dockerinstall
- 스프링부트
- 스프링부트api
- 우분투도커설치
- 스프링사진
- 출처 노마드코더
- 멀티폼
- 서버에도커설치
- 출처 따배도
Archives
- Today
- Total
MakerHyeon
49. Group Anagrams 본문
https://leetcode.com/problems/group-anagrams/description/
Group Anagrams - LeetCode
Group Anagrams - Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters e
leetcode.com
주어 word들을 똑같은 알파벳들 가지고있는것끼리 묶어 반환하는문제,
SOLUTION CODE
# PYTHON
1. key:value <=> word정렬값(sorted):original word
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
anagrams = collections.defaultdict(list) # 빈 리스트
# 각 단어를 정렬한값을 키로사용
# 원래단어를 value로 사용
for word in strs:
# 파이썬은 list는 키값이될수없음.
# 따라서 join을 사용해 str키값으로 반환
anagrams[''.join(sorted(word))].append(word)
return list(anagrams.values())
2. key:value <=> word count:original word
: 이렇게하면 해당 O(M*N)의 시간복잡도를 가져 sorted보다 더 효율적으로 처리 가능하다.
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
res = defaultdict(list) # 반환할 리스트
for s in strs:
count = [0] * 26 # a ... z
for c in s: # 각 s당
count[ord(c) - ord("a")] += 1 #나온 글자 횟수 카운팅
# 키:글자횟수 value:original해당글자.
#python에선 list가 키값 안되므로 tuple반환
res[tuple(count)].append(s)
return res.values()
# C++
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> ans;
unordered_map<string, vector<string>> mp;
/*
Consider example 1 : strs = ["eat","tea","tan","ate","nat","bat"]
After the below opeartion of for loop map will contain
aet -- eat, tea, ate
ant -- tan, nat
abt -- bat
*/
/*
키값은 str정렬해서 넣고, value는 original word
*/
for(int i = 0; i < strs.size() ; i++){
string s = strs[i];
sort(strs[i].begin(),strs[i].end());
mp[strs[i]].push_back(s);
}
//now simply put the elements of second column of map in ans
for(auto i : mp)
{
ans.push_back(i.second);
}
return ans;
}
};
●Join은 list 를 문자열 Str로 반환한다.
●sort,sorted차이?
sort 함수는 리스트명.sort( ) 형식으로 "리스트형의 메소드"이며 리스트 원본값을 직접 수정
sorted 함수는 sorted( 리스트명 ) 형식으로 "내장 함수"이며 리스트 원본 값은 그대로이고 정렬 값을 반환
'Algorithm > LeetCode' 카테고리의 다른 글
[LeetCode] 155. Min Stack (0) | 2023.01.05 |
---|---|
[LeetCode] 36. Valid Sudoku (0) | 2023.01.04 |
682. Baseball Game (0) | 2023.01.02 |
1929. Concatenation of Array (0) | 2023.01.01 |
347. Top K Frequent Elements (0) | 2022.12.22 |
Comments