Approach
Traverse the string from position zero till end of length
maintain a hashmap of already visited characters
Maintain current substring with non-repeating characters with the help of a start and end index.
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.