Question: C++ question:I need to fix this code that brings the right answer for only 'abc' type input not for 'aabbcc' implement a function to find
C++ question:I need to fix this code that brings the right answer for only 'abc' type input not for 'aabbcc'
implement a function to find the length of the longest substring without repeating characters for a given string. For example, the longest substring without repeating letters for abcabcbb is abc, and the length is 3. For string bbbbb the longest substring is b, with the length of 1.You can use either character array or string class to store the string.
#include
#include
#include
using namespace std;
void lengthOfLongestSubstring(string s) {
int i = 0, max = 0, offset = -1;
int arr[256];
string substr = "";
fill_n(arr, 256, -1);
for (i = 0; i < s.length(); i++) {
int si = (int)s[i];
offset = std::max(offset, arr[si]);
max = std::max(max, i - offset);
arr[si] = i;
}
substr = s.substr(0, max);
cout << "the longest substring without repeating letters for \"" << s << "\" is \"" << substr << "\" and the length is " << max << endl;
}
int main()
{
cout << "Enter string ";
string s;
cin >> s;
lengthOfLongestSubstring(s);
system("pause");
return 0;
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
