diff --git a/include/s0003_longest_substring_without_repeating_characters.hpp b/include/s0003_longest_substring_without_repeating_characters.hpp new file mode 100644 index 0000000..e1f6f9b --- /dev/null +++ b/include/s0003_longest_substring_without_repeating_characters.hpp @@ -0,0 +1,21 @@ +#ifndef S0003_LONGEST_SUBSTRING_WITHOUT_REPEATING_CHARACTERS_HPP +#define S0003_LONGEST_SUBSTRING_WITHOUT_REPEATING_CHARACTERS_HPP + +#include +#include + +class Solution { + public: + /** + * @brief Longest Substring Without Repeating Characters + * + * Given a string `s`, find the length of the **longest substring** without + * repeating characters. + * + * @param s the given string + * @return the longest substring without repeating characters + */ + int lengthOfLongestSubstring(std::string s); +}; + +#endif diff --git a/src/s0003_longest_substring_without_repeating_characters.cpp b/src/s0003_longest_substring_without_repeating_characters.cpp new file mode 100644 index 0000000..b8e8a9b --- /dev/null +++ b/src/s0003_longest_substring_without_repeating_characters.cpp @@ -0,0 +1,26 @@ +#include "s0003_longest_substring_without_repeating_characters.hpp" + +int Solution::lengthOfLongestSubstring(std::string s) { + // index_forward points to the frontmost element + // index_backward points to the last repeated element + // + // for + // check if index_forward pointed element exists in hash map + // if exists, index_backward = max(index_backward, the index of + // this element) + // push + // index_forward += 1 + // len = max(index_forward, index_backward) + std::map map; + int index_backward{-1}; + int index_forward{0}; + int len{0}; + for (; index_forward < s.length(); index_forward++) { + if (map.count(s[index_forward]) == 1) { + index_backward = std::max(index_backward, map.at(s[index_forward])); + } + map[s[index_forward]] = index_forward; + len = std::max(len, index_forward - index_backward); + } + return len; +} diff --git a/tests/s0003_longest_substring_without_repeating_characters.cpp b/tests/s0003_longest_substring_without_repeating_characters.cpp new file mode 100644 index 0000000..cfbe224 --- /dev/null +++ b/tests/s0003_longest_substring_without_repeating_characters.cpp @@ -0,0 +1,21 @@ +#include "s0003_longest_substring_without_repeating_characters.hpp" + +#include + +TEST(Problem3, Case1) { + std::string s{std::string("abcabcbb")}; + Solution solution; + EXPECT_EQ(solution.lengthOfLongestSubstring(s), 3); +} + +TEST(Problem3, Case2) { + std::string s{std::string("bbbbb")}; + Solution solution; + EXPECT_EQ(solution.lengthOfLongestSubstring(s), 1); +} + +TEST(Problem3, Case3) { + std::string s{std::string("pwwkew")}; + Solution solution; + EXPECT_EQ(solution.lengthOfLongestSubstring(s), 3); +}