중복 문자 질문
조회수 540회
문제)
['hong', 'a', 'a', 'a'], ['hong', 'a', 'b'], ['park', 'a', 'b', 'c'], ['hong', 'e', 'f', 'g'], ['park', 'a', 'a', 'b', 'b']
다음과 같은 배열이 주어 질때,
hong이 가지고 있는 알파벳( 중복x) a,b,e,f,g => 5개
park이 가지고 있는 알파벳( 중복x) a.b.c => 3개
따라서 hong이 가지고 있는 알파벳이 제일 많다.
출력) 서로 다른 알파벳을 제일 많이 가지고 있는 사람의 이름 출력 , (이름은 항상 배열의 앞에 옴) 'hong'
다음과 같은 문제를 풀려고 합니다.
map이나 해쉬테이블을 사용해서 풀려고했는데... 어떻게 풀어야할지 감이` 안와서 질문드려요...
풀이의 큰 개요를 알려주세요ㅠ (언어 c++)
-
(•́ ✖ •̀)
알 수 없는 사용자
1 답변
-
#include <algorithm> #include <iostream> #include <map> #include <set> #include <string> #include <vector> void sort_display(std::map<std::string, std::set<std::string>> &dict) { std::vector<std::pair<std::string, std::set<std::string>>> copy(dict.begin(), dict.end()); // sort by size() of letter set std::sort(copy.begin(), copy.end(), [](auto& a, auto& b) { return a.second.size() > b.second.size(); }); // print sorted vector for (auto& d : copy) { std::cout << d.first << ": "; for (auto e : d.second) { std::cout << e << ", "; } std::cout << std::endl; } } int main() { std::vector<std::vector<std::string>> data = { { "hong","a","a","a" }, { "hong","a","b" }, { "park","a","b","c" }, { "hong","e","f","g"},{"park","a","a","b","b"} }; std::map<std::string, std::set<std::string>> dict; std::string name; std::set<std::string> s; // merge data into a map structure, by the first string of each data. for (auto row : data) { name = row[0]; // first element is the name s = std::set<std::string>(row.begin() + 1, row.end()); // other elements are converted into a set if (dict.find(name) == dict.end()) { dict[name] = s; } else { dict[name].insert(s.begin(), s.end()); } } sort_display(dict); return 0; }
댓글 입력