Leetcode Longest Substring Without Repeating Characters problem solution in Java programming

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,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *