Skip to content

Commit 2b8562e

Browse files
committed
Problem03 using StringBuilder
1 parent 6df3e94 commit 2b8562e

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.shekhargulati.leetcode;
2+
3+
/**
4+
* Longest substring without repeating characters
5+
*/
6+
public class Problem03 {
7+
8+
public static String substring(final String input) {
9+
StringBuilder subStr = new StringBuilder();
10+
String[] chars = input.split("");
11+
for (String ch : chars) {
12+
int indexCh = subStr.indexOf(ch);
13+
if (indexCh == -1) {
14+
subStr.append(ch);
15+
} else {
16+
subStr = new StringBuilder(subStr.substring(indexCh + 1));
17+
subStr.append(ch);
18+
}
19+
}
20+
return subStr.toString();
21+
}
22+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.shekhargulati.leetcode;
2+
3+
import org.junit.Test;
4+
5+
import static org.hamcrest.CoreMatchers.equalTo;
6+
import static org.junit.Assert.assertThat;
7+
8+
public class Problem03Test {
9+
10+
@Test
11+
public void shouldFindLongestSubstring() throws Exception {
12+
final String input = "abcabc";
13+
String substring = Problem03.substring(input);
14+
assertThat(substring, equalTo("abc"));
15+
}
16+
17+
@Test
18+
public void shouldFindLongestSubstringIn_bbbbb() throws Exception {
19+
final String input = "bbbb";
20+
String substring = Problem03.substring(input);
21+
assertThat(substring, equalTo("b"));
22+
}
23+
}

0 commit comments

Comments
 (0)