I have been trying to implement logic but only partialy able to implement.
Could someone predict what is logic i am missing and how to improve my code and guide me where i need to make changes in my code only.
Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
's' consists of English letters, digits, symbols and spaces.
Code :
input 1 : s = "pwwkew"
input 2 : s = "abcabcbb"
input 3 : s = "cdd"
input 4 : s = "abcabcbb"
You can use able 4 sample input and try one by one to get expected output.
s = "abcabcbb"
temp = ''
cnt = 0
for i in range(len(s)):
if s[i] not in temp:
temp = temp + s[i]
else:
temp = temp.replace(temp[:temp.index(s[i])],'')
print(temp)
>Solution :
Let take the example of abcabcbb.
So in your code, in the else block you are trying to change temp to a string which doesn’t contain any repeating character but contains the character that is being considered in the iteration.
else:
temp = temp.replace(temp[:temp.index(s[i])],'')
Here, let’s say temp was abc in last iteration and s[i] is now a. So, temp.index(s[i]) is 0 and temp[:0] is ''. And tempultimately becomesabc` again.
I think it should be temp.replace(temp[:temp.index(s[i]) + 1],'') instead as we want to remove the string starting from index 0 to the index containing the repeating character. Also you want to add the character that is being considered in this iteration in temp. So, ultimately it will look like –
else:
temp = temp.replace(temp[:temp.index(s[i]) + 1],'') + s[i]
The only thing remaining is to track the maximum length of the substring which can be done in the following way –
s = "abcabcbb"
temp = ''
cnt = 0
for i in range(len(s)):
if s[i] not in temp:
temp = temp + s[i]
else:
temp = temp.replace(temp[:temp.index(s[i]) + 1],'') + s[i]
cnt = max(cnt, len(temp))
print(cnt)