Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Problem with Longest Substring Without Repeating Characters


I am having difficulty with the following problem post: longest substring without repeating characters. I'm using Java to write my code, and I'm getting an output of 0. I can't figure out what is wrong with my code.

Here is the code I'm using: 

public int lengthOfLongestSubstring(String s) {

  int n = s.length(), ans = 0;

  Map<Character, Integer> map = new HashMap<>();

  for (int j = 0, i = 0; j < n; j++) {

    if (map.containsKey(s.charAt(j))) {

      i = Math.max(map.get(s.charAt(j)), i);


    ans = Math.max(ans, j - i + 1);

    map.put(s.charAt(j), j + 1);


  return ans;


I would really appreciate some help with this. Thank you!

Sign In or Register to comment.