Pages

Find longest non-repeating substring from a given string in Java

 

Approach

  1. Traverse the string from position zero till end of length

  2. maintain a hashmap of already visited characters

  3. Maintain current substring with non-repeating characters with the help of a start and end index.

  4. maintain the longest non-repeating substring in result variable

String getNonRepeatingSubstring(String input) { Map<Character, Integer> visited = new HashMap<>(); String result = ""; for (int start = 0, end = 0; end < input.length(); end++) { char currChar = input.charAt(end); if (visited.containsKey(currChar)) { start = Math.max(visited.get(currChar) + 1, start); } if (result.length() < end - start + 1) { result = input.substring(start, end + 1); } visited.put(currChar, end); } return result; }

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.