Skip to content

Commit 8529473

Browse files
Create Longest_Substring_Without_Repeating_Characters.cpp
Added a new solution file Longest_Substring_Without_Repeating_Characters.cpp, which implements a C++ program to find the length of the longest substring without repeating characters in a given string. This program uses a sliding window approach along with a hash map to store the last seen index of each character, allowing for efficient tracking of unique substrings. The code takes user input for the string and outputs the maximum length of any substring without duplicate characters. Comments and an example are included for clarity.
1 parent 64d8b48 commit 8529473

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
#include <iostream>
2+
#include <unordered_map>
3+
#include <string>
4+
using namespace std;
5+
6+
// Function to find the length of the longest substring without repeating characters
7+
int lengthOfLongestSubstring(const string &s) {
8+
unordered_map<char, int> charIndexMap;
9+
int maxLength = 0;
10+
int start = 0;
11+
12+
for (int end = 0; end < s.length(); end++) {
13+
char currentChar = s[end];
14+
15+
// If the character is already in the map and is within the current window
16+
if (charIndexMap.find(currentChar) != charIndexMap.end() && charIndexMap[currentChar] >= start) {
17+
start = charIndexMap[currentChar] + 1;
18+
}
19+
20+
// Update the last seen index of the current character
21+
charIndexMap[currentChar] = end;
22+
23+
// Calculate the max length of substring
24+
maxLength = max(maxLength, end - start + 1);
25+
}
26+
return maxLength;
27+
}
28+
29+
int main() {
30+
string input;
31+
cout << "Enter a string: ";
32+
cin >> input;
33+
34+
int result = lengthOfLongestSubstring(input);
35+
cout << "The length of the longest substring without repeating characters is: " << result << endl;
36+
37+
return 0;
38+
}
39+
40+
/*
41+
Example:
42+
Input: "abcabcbb"
43+
Explanation:
44+
- The longest substring without repeating characters is "abc", which has a length of 3.
45+
- As we iterate through the string:
46+
- Start with "a" -> length 1
47+
- Add "b" -> "ab" -> length 2
48+
- Add "c" -> "abc" -> length 3
49+
- "a" repeats, so move the start to the next character -> "bca" (length still 3)
50+
- Continue until the end, with the longest substring remaining "abc".
51+
Output: 3
52+
53+
Input: "bbbbb"
54+
Explanation:
55+
- The longest substring without repeating characters is "b", which has a length of 1.
56+
Output: 1
57+
*/

0 commit comments

Comments
 (0)