Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save myrtleTree33/2bfc51f2ecaecd9a848bcc6b2dfb4024 to your computer and use it in GitHub Desktop.
Save myrtleTree33/2bfc51f2ecaecd9a848bcc6b2dfb4024 to your computer and use it in GitHub Desktop.
import java.util.HashSet;
import java.util.Set;
public class LongestNonrepeatingSubstring {
public static void main(String[] args) {
String input = "pwwkew";
System.out.println(longestNonrepeatingSubstr(input));
}
private static int longestNonrepeatingSubstr(String input) {
int max = 0;
int count = 0;
Set<Character> lut = new HashSet<>();
for (int i = 0; i < input.length(); i++) {
char currChar = input.charAt(i);
// Reset counter if needed
if (lut.contains(currChar)) {
if (max < count) {
max = count;
}
count = 0;
lut = new HashSet<>();
}
// Increment counter
count++;
lut.add(currChar);
}
return max;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment