In the Leetcode Longest Substring Without Repeating Characters problem solution in Java programming Given a string s, find the length of the longest substring without repeating characters.
Leetcode Longest Substring Without Repeating Characters problem solution in Java programming
import java.util.HashMap;
public class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap<Character, Integer> hmap = new HashMap<Character, Integer>();
int start = 0, end = 0;
int maxLen = 0;
while(end < s.length()) {
if(hmap.containsKey(s.charAt(end)) && (hmap.get(s.charAt(end)) >= start)) {
start = hmap.get(s.charAt(end)) + 1;
} else if(((end - start) + 1) > maxLen){
//not in the table => put the k,v to the hashtable
//and update the max length
maxLen = (end-start+1);
}
hmap.put(s.charAt(end), end);
end += 1;
}
return maxLen;
}
}
Also read,
- Leetcode Longest Substring Without Repeating Characters problem solution in C
- Leetcode Longest Substring Without Repeating Characters problem solution in C++
- Leetcode Longest Substring Without Repeating Characters problem solution in Python
- Leetcode Longest Substring Without Repeating Characters problem solution in C#