Skip to content

Commit c670a80

Browse files
authored
PR #12: Longest Substring Without Repeating Characters
Create Longest_Substring_Without_Repeating_Characters.cpp Merge pull request #12 from RohithaAiswarya16/patch-1
2 parents 64d8b48 + 7c02489 commit c670a80

File tree

1 file changed

+63
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)