Skip to content

Commit d7cc258

Browse files
committed
feat: solved 3
1 parent 7fa583c commit d7cc258

File tree

1 file changed

+41
-0
lines changed
  • src/com/fghpdf/LongestSubstringWithoutRepeatingCharacters

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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+
}

0 commit comments

Comments
 (0)