Q-10 PepCoding | Longest Substring With Non Repeating Characters
Tue Jan 24 2023 13:42:58 GMT+0000 (Coordinated Universal Time)
Saved by
@Ayush_dabas07
class Solution {
public int lengthOfLongestSubstring(String s) {
//2 HM to keep track of characters & answer string
HashMap<Character,Integer> map1 = new HashMap<>();
int ans = 0 ;
//pointers to keep track of window
int i = 0 , j = 0;
//acquiring and releasing while traversing the array
for(i = 0 ; i< s.length(); i++){
//storing in map and updating ccc
char ch = s.charAt(i);
map1.put(ch,map1.getOrDefault(ch,0)+1);
//now that we have valid substring we will store this and check for smaller
//substring by removing character from behind one by one
while(map1.get(ch)==2){
//removing character & updating ccc
char temp = s.charAt(j);
//updating ccc
if(map1.get(temp) == 1)
map1.remove(temp);
else
map1.put(temp , map1.get(temp)-1);
j++;
}
String pans = s.substring(j , i+1);
System.out.println(pans);
ans = Math.max(ans , pans.length());
}
return ans;
}
}
content_copyCOPY
https://www.pepcoding.com/resources/data-structures-and-algorithms-in-java-levelup/hashmap-and-heaps/longest-substring-with-unique-characters-official/ojquestion
Comments