Skip to content

Commit 09261fb

Browse files
committed
BAEL-2393: Longest Sub-string without repeating characters.
1 parent 5aef6d9 commit 09261fb

2 files changed

Lines changed: 71 additions & 0 deletions

File tree

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package com.baeldung.algorithms.string;
2+
3+
import java.util.HashMap;
4+
import java.util.HashSet;
5+
import java.util.Map;
6+
import java.util.Set;
7+
8+
public class LongestSubstringNonRepeatingCharacters {
9+
10+
public static String getNonRepeatingCharactersBruteForce(String input) {
11+
String output = "";
12+
for (int start = 0; start < input.length(); start++) {
13+
Set<Character> visited = new HashSet<>();
14+
int end = start;
15+
for (; end < input.length(); end++) {
16+
char currChar = input.charAt(end);
17+
if (visited.contains(currChar)) {
18+
break;
19+
} else {
20+
visited.add(currChar);
21+
}
22+
}
23+
if (output.length() < end - start + 1) {
24+
output = input.substring(start, end);
25+
}
26+
}
27+
return output;
28+
}
29+
30+
public static String getNonRepeatingCharacters(String input) {
31+
Map<Character, Integer> visited = new HashMap<>();
32+
String output = "";
33+
for (int start = 0, end = 0; end < input.length(); end++) {
34+
char currChar = input.charAt(end);
35+
if(visited.containsKey(currChar)) {
36+
start = Math.max(visited.get(currChar)+1, start);
37+
}
38+
if(output.length() < end - start + 1) {
39+
output = input.substring(start, end+1);
40+
}
41+
visited.put(currChar, end);
42+
}
43+
return output;
44+
}
45+
46+
public static void main(String[] args) {
47+
String input = "CODINGISAWESOME";
48+
System.out.println(getNonRepeatingCharacters(input));
49+
}
50+
51+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.baeldung.algorithms.string;
2+
3+
import org.junit.jupiter.api.Assertions;
4+
import org.junit.jupiter.api.Test;
5+
6+
public class LongestSubstringNonRepeatingCharactersTest {
7+
8+
@Test
9+
void givenString_whenGetNonRepeatingCharactersBruteForceCalled_thenResultFoundAsExpected() {
10+
String input = "CODINGISAWESOME";
11+
Assertions.assertEquals("NGISAWE", LongestSubstringNonRepeatingCharacters.getNonRepeatingCharactersBruteForce(input));
12+
}
13+
14+
@Test
15+
void givenString_whenGetNonRepeatingCharactersCalled_thenResultFoundAsExpected() {
16+
String input = "CODINGISAWESOME";
17+
Assertions.assertEquals("NGISAWE",LongestSubstringNonRepeatingCharacters.getNonRepeatingCharacters(input));
18+
}
19+
20+
}

0 commit comments

Comments
 (0)