File tree Expand file tree Collapse file tree 3 files changed +69
-1
lines changed
_includes/_root/longest-substring-with-at-most-two-distinct-characters
longest-substring-with-at-most-two-distinct-characters Expand file tree Collapse file tree 3 files changed +69
-1
lines changed Original file line number Diff line number Diff line change
1
+ public class Solution {
2
+
3
+ static class Context {
4
+ int start = 0 ;
5
+ int end = 0 ;
6
+
7
+ Map <Character , Integer > counts = new HashMap <Character , Integer >();
8
+
9
+ int len (){
10
+ return end - start + 1 ;
11
+ }
12
+
13
+ void add (Character c ) {
14
+ Integer i = counts .get (c );
15
+ if (i == null ){
16
+ i = 0 ;
17
+ }
18
+
19
+ i ++;
20
+
21
+ counts .put (c , i );
22
+ }
23
+
24
+ void remove (Character c ){
25
+ Integer i = counts .remove (c );
26
+ if (i == null ){
27
+ return ;
28
+ }
29
+
30
+ i --;
31
+
32
+ if (i > 0 ){
33
+ counts .put (c , i );
34
+ }
35
+ }
36
+ }
37
+
38
+ public int lengthOfLongestSubstringTwoDistinct (String s ) {
39
+
40
+ char [] S = s .toCharArray ();
41
+
42
+ if (S .length == 0 ) return 0 ;
43
+
44
+ int max = 1 ;
45
+
46
+ Context context = new Context ();
47
+
48
+ for (int i = 0 ; i < S .length ; i ++){
49
+ Character c = S [i ];
50
+
51
+ context .add (c );
52
+ context .end = i ;
53
+
54
+ // need trim to 2
55
+
56
+ for (int j = context .start ; context .counts .size () > 2 ;j ++) {
57
+ Character _c = S [j ];
58
+ context .remove (_c );
59
+ context .start = j + 1 ;
60
+ }
61
+
62
+ max = Math .max (context .len (), max );
63
+ }
64
+
65
+
66
+ return max ;
67
+ }
68
+ }
Original file line number Diff line number Diff line change 1
1
---
2
2
layout : solution
3
3
title : Longest Substring with At Most Two Distinct Characters
4
- date : 2014-11-26 19:04:52+08:00
4
+ date : 2014-11-26 19:06:13 +0800
5
5
---
6
6
{% assign leetcode_name = {{page.path | remove: '/index.md'}} %}
7
7
{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_ root/' }} %}
You can’t perform that action at this time.
0 commit comments