3. The longest string without repetition (lengthOfLongestSubstring)
1. python
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if not s:
return 0
cur_len,max_len=0,0
s_len = len(s)
left = 0
hashSet = set()
for i in range(s_len):
cur_len+=1
while s[i] in hashSet:
hashSet.remove(s[left])
left+=1
cur_len-=1
if cur_len>max_len:
max_len = cur_len
hashSet.add(s[i])
return max_len
2. Java
class Solution {
public int lengthOfLongestSubstring(String s) {
Set<Character> hashSet = new HashSet<Character>();
int cur=0;
int max=0;
int left=0;
for(int i=0;i<s.length();i++){
++cur;
while(hashSet.contains(s.charAt(i))){
hashSet.remove(s.charAt(left));
left++;
cur--;
}
if(cur>max){
max=cur;
}
hashSet.add(s.charAt(i));
}
return max;
}
}