Skip to content

Commit 8dc9fbb

Browse files
authored
Merge pull request #578 from talk2sourajit/patch-1
Create Longest_Substring.cpp
2 parents 54b9d6e + 9a71307 commit 8dc9fbb

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

Longest_Substring.cpp

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// C++ program to find the length of the longest substring
2+
// without repeating characters
3+
#include <bits/stdc++.h>
4+
using namespace std;
5+
// This function returns true if all characters in str[i..j]
6+
// are distinct, otherwise returns false
7+
bool areDistinct(string str, int i, int j)
8+
{
9+
vector<bool> visited(26);
10+
for (int k = i; k <= j; k++) {
11+
if (visited[str[k] - 'a'] == true)
12+
return false;
13+
visited[str[k] - 'a'] = true;
14+
}
15+
return true;
16+
}
17+
18+
// Returns length of the longest substring
19+
// with all distinct characters.
20+
int longestUniqueSubsttr(string str)
21+
{
22+
int n = str.size();
23+
int res = 0; // result
24+
for (int i = 0; i < n; i++)
25+
for (int j = i; j < n; j++)
26+
if (areDistinct(str, i, j))
27+
res = max(res, j - i + 1);
28+
return res;
29+
}
30+
31+
// Driver code
32+
int main()
33+
{
34+
string str = "bobisbobbydeol";
35+
cout << "The input string is " << str << endl;
36+
int len = longestUniqueSubsttr(str);
37+
cout << "The length of the longest non-repeating "
38+
"character substring is "
39+
<< len;
40+
return 0;
41+
}

0 commit comments

Comments
 (0)