TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
longest_substring_without_repeating_characters.cpp
Go to the documentation of this file.
1
27#include <iostream> // for IO Operations
28#include <unordered_map> // for std::unordered_map
29#include <deque> // for std::deque
30#include <string> // for string class/string datatype which is taken as input
31#include <cassert> // for assert
32
38public:
44 int lengthOfLongestSubstring(std::string s) {
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 }
86};
87
92static void tests() {
94 assert(soln.lengthOfLongestSubstring("abcabcbb") == 3);
95 assert(soln.lengthOfLongestSubstring("bbbbb") == 1);
96 assert(soln.lengthOfLongestSubstring("pwwkew") == 3);
97 assert(soln.lengthOfLongestSubstring("") == 0); // Test case for empty string
98 assert(soln.lengthOfLongestSubstring("abcdef") == 6); // Test case for all unique characters
99 assert(soln.lengthOfLongestSubstring("a") == 1); // Single character
100 std::cout << "All test cases passed!" << std::endl;
101}
102
107int main() {
108 tests(); // run self-test implementations
109 return 0;
110}
Class that solves the Longest Substring Without Repeating Characters problem.
int lengthOfLongestSubstring(std::string s)
Function to find the length of the longest substring without repeating characters.
static void tests()
Self-test implementations.