Longest Substring Without Repeating Characters
This commit is contained in:
parent
7d5f585e91
commit
e5239dbae7
@ -0,0 +1,21 @@
|
|||||||
|
#ifndef S0003_LONGEST_SUBSTRING_WITHOUT_REPEATING_CHARACTERS_HPP
|
||||||
|
#define S0003_LONGEST_SUBSTRING_WITHOUT_REPEATING_CHARACTERS_HPP
|
||||||
|
|
||||||
|
#include <map>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
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
|
26
src/s0003_longest_substring_without_repeating_characters.cpp
Normal file
26
src/s0003_longest_substring_without_repeating_characters.cpp
Normal file
@ -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<char, int> 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;
|
||||||
|
}
|
@ -0,0 +1,21 @@
|
|||||||
|
#include "s0003_longest_substring_without_repeating_characters.hpp"
|
||||||
|
|
||||||
|
#include <gtest/gtest.h>
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user