File tree Expand file tree Collapse file tree 2 files changed +46
-0
lines changed
main/java/s0003.longest.substring.without.repeating.characters
test/java/s0003.longest.substring.without.repeating.characters Expand file tree Collapse file tree 2 files changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ package s0003 .longest .substring .without .repeating .characters ;
2+
3+ class Solution {
4+ public int lengthOfLongestSubstring (String s ) {
5+ int lastIndices [] = new int [256 ];
6+ for (int i = 0 ; i <256 ; i ++) {
7+ lastIndices [i ] = -1 ;
8+ }
9+
10+ int maxLen = 0 ;
11+ int curLen = 0 ;
12+ int start = 0 ;
13+ int bestStart = 0 ;
14+ for (int i = 0 ; i < s .length (); i ++) {
15+ char cur = s .charAt (i );
16+ if (lastIndices [cur ] < start ) {
17+ lastIndices [cur ] = i ;
18+ curLen ++;
19+ } else {
20+ int lastIndex = lastIndices [cur ];
21+ start = lastIndex + 1 ;
22+ curLen = i - start + 1 ;
23+ lastIndices [cur ] = i ;
24+ }
25+
26+ if (curLen > maxLen ) {
27+ maxLen = curLen ;
28+ bestStart = start ;
29+ }
30+ }
31+
32+ return maxLen ;
33+ }
34+ }
Original file line number Diff line number Diff line change 1+ package s0003 .longest .substring .without .repeating .characters ;
2+
3+ import static org .hamcrest .CoreMatchers .equalTo ;
4+ import static org .hamcrest .MatcherAssert .assertThat ;
5+ import org .junit .Test ;
6+
7+ public class SolutionTest {
8+ @ Test
9+ public void lengthOfLongestSubstring () {
10+ assertThat (new Solution ().lengthOfLongestSubstring ("abcabcbb" ), equalTo (3 ));
11+ }
12+ }
You can’t perform that action at this time.
0 commit comments