File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
src/com/fghpdf/LongestSubstringWithoutRepeatingCharacters Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .fghpdf .LongestSubstringWithoutRepeatingCharacters ;
2
+
3
+ import java .util .HashMap ;
4
+ import java .util .Map ;
5
+
6
+ /**
7
+ * @author fghpdf
8
+ * @date 2019/11/9
9
+ *
10
+ * https://leetcode.com/problems/longest-substring-without-repeating-characters/
11
+ * two pointer and a map to save the char position
12
+ * first pointer is to loop string
13
+ * second pointer is to jump to the repeat position
14
+ * when I found repeat char, the substring is over
15
+ * so I should start from the last char of the substring
16
+ **/
17
+ public class Solution {
18
+ public int lengthOfLongestSubstring (String s ) {
19
+ if (s == null || "" .equals (s )) {
20
+ return 0 ;
21
+ }
22
+ Map <Character , Integer > position = new HashMap <>(26 );
23
+
24
+ int maxLength = -1 ;
25
+ for (int i = 0 , repeatPosition = 0 ; i < s .length (); i ++) {
26
+ char c = s .charAt (i );
27
+ if (position .get (c ) != null ) {
28
+ repeatPosition = Math .max (repeatPosition , position .get (c ) + 1 );
29
+ System .out .println (repeatPosition );
30
+ }
31
+ position .put (c , i );
32
+ maxLength = Math .max (i - repeatPosition + 1 , maxLength );
33
+ }
34
+ return maxLength ;
35
+ }
36
+
37
+ public static void main (String [] args ) {
38
+ Solution sol = new Solution ();
39
+ System .out .println (sol .lengthOfLongestSubstring ("abcabcdd" ));
40
+ }
41
+ }
You can’t perform that action at this time.
0 commit comments