Skip to content

Commit

Permalink
Uncommon Words from Two Sentences
Browse files Browse the repository at this point in the history
  • Loading branch information
hikjik committed Oct 20, 2023
1 parent 026d25e commit e068540
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 0 deletions.
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -819,6 +819,7 @@ add_task(two-sum-iv-input-is-a-bst)
add_task(ugly-number)
add_task(ugly-number-ii)
add_task(ugly-number-iii)
add_task(uncommon-words-from-two-sentences)
add_task(uncrossed-lines)
add_task(unique-binary-search-trees)
add_task(unique-binary-search-trees-ii)
Expand Down
1 change: 1 addition & 0 deletions solutions/uncommon-words-from-two-sentences/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
add_catch(test_uncommon_words_from_two_sentences test.cpp)
26 changes: 26 additions & 0 deletions solutions/uncommon-words-from-two-sentences/solution.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#pragma once

#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>

class Solution {
public:
static std::vector<std::string> uncommonFromSentences(std::string s1,
std::string s2) {
std::stringstream stream(s1 + " " + s2);
std::unordered_map<std::string, int> counter;
for (std::string word; stream >> word;) {
++counter[word];
}

std::vector<std::string> uncommon;
for (const auto &[word, frequency] : counter) {
if (frequency == 1) {
uncommon.push_back(word);
}
}
return uncommon;
}
};
31 changes: 31 additions & 0 deletions solutions/uncommon-words-from-two-sentences/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#include <catch.hpp>

#include <solution.hpp>

TEST_CASE("Simple") {
struct TestCase {
std::string s1;
std::string s2;
std::vector<std::string> expected;
};

std::vector<TestCase> test_cases{
{
.s1 = "this apple is sweet",
.s2 = "this apple is sour",
.expected{"sweet", "sour"},
},
{
.s1 = "apple apple",
.s2 = "banana",
.expected{"banana"},
},
};

for (auto [s1, s2, expected] : test_cases) {
auto actual = Solution::uncommonFromSentences(s1, s2);
std::sort(actual.begin(), actual.end());
std::sort(expected.begin(), expected.end());
REQUIRE(expected == actual);
}
}

0 comments on commit e068540

Please sign in to comment.