[leetcode]3. Longest Substring Without Repeating Characters

来源:互联网 发布:婚礼效果图软件 编辑:程序博客网 时间:2024/05/03 19:57

题目大意:

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring"pwke" is a subsequence and not a substring.

Subscribe to see which companies asked this question.


分析:

1.HashMap: key -> string s charAt之后的每一个字母

    value -> 每一个字母的索引

2.没有重复字母出现时,max是i+1-position,此时的position=0,其实max就是i+1,而是当前遍历的字母的索引,所以i+1就是当前substring的长度;

   出现重复的时候,i+1-position表达就是两次重复出现的间隔,例如"abcabcbb",就是两个a的间隔是3

3.当有重复出现时,position的值才进行更新,position=Math.max(position, map.get(cha)+1);

   之后的map.put(cha, i), i则是重复的字母的重复出现位置的索引;

   有了这样的基础,再进行i+1-position的更新。

4.position的值更新时,不可以position=Math.max(position, map.get(cha)),因为若string=“a”,只有一个字母的情况下结果输出0,显然不对

public static int lengthOfLongestSubstring(String s) {Map<Character,Integer> map=new HashMap<>();int max=0;int position=0;for(int i=0;i<s.length();i++){char cha=s.charAt(i);if(map.containsKey(cha)){position=Math.max(position, map.get(cha)+1);}map.put(cha, i);max=Math.max(max, i+1-position);}return max;            }




0 0