0%

leetcode 3 Solution

代码解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.demo.s3;

import java.util.HashMap;
import java.util.Map;

/**
* 给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
*/
public class Solution {

public int lengthOfLongestSubstring(String s) {
//字符串 字符数组
char[] chars = s.toCharArray();
//游标 子串
int start = 0;
//子串最大长度
int max = 0;
//出现字符 及对应的下标<字符, 最近一次出现的下标>
Map<Character, Integer> cs = new HashMap<>();
for(int i= 0; i < chars.length; i++) {
//子串中字符上次出现位置
Integer lastExist = cs.get(chars[i]);
//如果已经出现过该字符且在子串中
if(lastExist!=null && lastExist >= start) {
// 则从字符出现重复后端下一个位置开始
start = lastExist + 1;
//如果字符长度大于目前记录的最大长度
} else if(i - start + 1 > max) {
//则更新最大长度记录
max = i - start + 1;
}
//每次遍历把字符 及出现的下标记录下来
cs.put(chars[i], i);
}
return max;
}

public static void main(String[] args) {

}
}