Algorithms_in_C++ 1.0.0
Set of 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.

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.
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.
50 int n = s.length();
51
52 // Deque to remove from back if repeating characters are present.
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 }
T pop_front(T... args)
T push_back(T... args)
T size(T... args)
Here is the call graph for this function:

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