
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

- 使用HashMap,遍历字符串,将每个字符存入map中。
- 定义变量left,每次遍历时,使用containsKey判断该字符是否已经存在,若存在且map中取出的i大于left,则令left=i+1,则当前不重复子串长度为i-left+1
- 定义变量max来表示最长无重复子串,每次循环后,判断max本身与当前遍历的不重复子串i-left+1的大小,令max为最大值。
- 循环结束后,max的值即为无重复字符的最长字串。
完整代码如下
public class ReString {
public static int lengthOfLongestSubstring(String s) {
if (s.length()==0) {
return 0;
}
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int max = 0;
int left = 0;
for(int i = 0; i < s.length(); i ++){
if(map.containsKey(s.charAt(i))){
left = Math.max(left,map.get(s.charAt(i)) + 1);
}
map.put(s.charAt(i),i);
max = Math.max(max,i-left+1);
}
return max;
}
public static void main(String[] args) {
int i = lengthOfLongestSubstring("abcabcbb");
System.out.println(i);
}
}