TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
Longest_Substring Class Reference

Class that solves the Longest Substring Without Repeating Characters problem. More...

Public Member Functions

int lengthOfLongestSubstring (std::string s)
 Function to find the length of the longest substring without repeating characters.
 

Detailed Description

Class that solves the Longest Substring Without Repeating Characters problem.

Definition at line 37 of file longest_substring_without_repeating_characters.cpp.

Member Function Documentation

◆ lengthOfLongestSubstring()

int Longest_Substring::lengthOfLongestSubstring ( std::string s)
inline

Function to find the length of the longest substring without repeating characters.

Parameters
sInput string.
Returns
Length of the longest substring.

Definition at line 44 of file longest_substring_without_repeating_characters.cpp.

44 {
45 // If the size of string is 1, then it will be the answer.
46 if (s.size() == 1) return 1;
47
48 // Map used to store the character frequency.
49 std::unordered_map<char, int> m;
50 int n = s.length();
51
52 // Deque to remove from back if repeating characters are present.
53 std::deque<char> temp;
54 std::deque<char> res;
55 int i, j;
56
57 // Sliding window approach using two pointers.
58 for (i = 0, j = 0; i < n && j < n;) {
59 m[s[j]]++;
60
61 // If repeating character found, update result and remove from the front.
62 if (m[s[j]] > 1) {
63 if (temp.size() > res.size()) {
64 res = temp;
65 }
66
67 while (m[s[j]] > 1) {
68 temp.pop_front();
69 m[s[i]]--;
70 i++;
71 }
72 }
73
74 // Add the current character to the deque.
75 temp.push_back(s[j]);
76 j++;
77 }
78
79 // Final check to update result.
80 if (temp.size() > res.size()) {
81 res = temp;
82 }
83
84 return res.size(); // Return the length of the longest substring.
85 }

The documentation for this class was generated from the following file: