Skip to content

Instantly share code, notes, and snippets.

@edwingsm
Last active January 28, 2025 07:59
Show Gist options
  • Save edwingsm/97f6c803d1b8a73cce7b490ca5dcce4c to your computer and use it in GitHub Desktop.
Save edwingsm/97f6c803d1b8a73cce7b490ca5dcce4c to your computer and use it in GitHub Desktop.
import java.util.HashMap;
class LongestUniqueSubstring {
static final int MAX_CHAR = 26;
static int bruteForce(String s) {
int n = s.length();
int res = 0;
for (int i = 0; i < n; i++) {
// Initializing all characters as not visited
boolean[] vis = new boolean[MAX_CHAR];
for (int j = i; j < n; j++) {
// If current character is visited
// Break the loop
if (vis[s.charAt(j) - 'a'] == true)
break;
// Else update the result if this window is larger,
// and mark current character as visited.
else {
res = Math.max(res, j - i + 1);
vis[s.charAt(j) - 'a'] = true;
}
}
}
return res;
}
static int findLongestSubstringWithoutRepeating(String s) {
HashMap<Character, Integer> charIndexMap = new HashMap<>();
int maxLength = 0;
int start = 0;
for (int end = 0; end < s.length(); end++) {
char currentChar = s.charAt(end);
if (charIndexMap.containsKey(currentChar)) {
start = Math.max(start, charIndexMap.get(currentChar) + 1);
}
charIndexMap.put(currentChar, end);
maxLength = Math.max(maxLength, end - start + 1);
}
return maxLength;
}
public static void main(String[] args) {
String s = "geeksforgeeks";
System.out.println(bruteForce(s));
System.out.println(findLongestSubstringWithoutRepeating(s));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment