File tree Expand file tree Collapse file tree
java-note-algorithm/src/main/java/com/leosanqing/leetcode/medium/string Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .leosanqing .leetcode .medium .string ;
2+
3+ import java .util .HashMap ;
4+ import java .util .Map ;
5+
6+ /**
7+ * @description: Given a string s, find the length of the longest substring without repeating characters.
8+ * <p>
9+ * 给定字符串s,找到最长子字符串的长度而不重复字符。
10+ * <p>
11+ * ` Example 1:
12+ * <p>
13+ * ` Input: s = "abcabcbb"
14+ * ` Output: 3
15+ * ` Explanation: The answer is "abc", with the length of 3.
16+ * ` Example 2:
17+ * <p>
18+ * ` Input: s = "bbbbb"
19+ * ` Output: 1
20+ * ` Explanation: The answer is "b", with the length of 1.
21+ * ` Example 3:
22+ * <p>
23+ * ` Input: s = "pwwkew"
24+ * ` Output: 3
25+ * ` Explanation: The answer is "wke", with the length of 3.
26+ * ` Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
27+ * ` Example 4:
28+ * <p>
29+ * ` Input: s = ""
30+ * ` Output: 0
31+ * <p>
32+ * ` @author: rtliu
33+ * ` @date: 2021/4/6 3:41 下午
34+ */
35+ public class _3_longest_substring_without_repeating_characters {
36+ public static void main (String [] args ) {
37+ System .out .println (lengthOfLongestSubstring ("abba" ));
38+ }
39+
40+ /**
41+ * 这个是典型的滑动窗口类的题型
42+ *
43+ * 我们遇到相同的字符就丢弃之前字符左边的所有字符
44+ * @param s
45+ * @return
46+ */
47+ public static int lengthOfLongestSubstring (String s ) {
48+ Map <Character , Integer > map = new HashMap <>(s .length () * 2 );
49+
50+ int result = 0 ;
51+ int head = 0 ;
52+
53+ for (int i = 0 ; i < s .length (); i ++) {
54+ char c = s .charAt (i );
55+
56+ if (map .containsKey (c ) && head < map .get (c )) {
57+ head = map .get (c );
58+ }
59+ // i+1 表示当前字符的实际位置
60+ result = Math .max (i + 1 - head , result );
61+ map .put (c , i + 1 );
62+ }
63+
64+ return result ;
65+ }
66+ }
You can’t perform that action at this time.
0 commit comments