LeetCode 3 Longest Substring Without Repeating Characters

来源:互联网 发布:淘宝服务公司 编辑:程序博客网 时间:2024/05/22 14:43

原题:(频率2)

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.





题意:求最长的无重复字母的子串



代码和思路

class Solution {    public int lengthOfLongestSubstring(String s) {        if(s.length()==0) return 0;                int max = 0;        //用map来记录出现的字符以及所在的位置        Map<Character,Integer> map = new HashMap<>();                for(int i=0,j=0;i<s.length();i++){            if(map.containsKey(s.charAt(i))){                //如果出现了重复的数字,那么重复的index小的数字就可以舍去,把指针j移动到舍去之后的位置                //如abca  原来i在c,j在0,那么长度是2-0+1=3. 现在i到了第二个a,我们得知第一个a在位置0,那么就跳过它,把j移动到1.-。                j = Math.max(j,map.get(s.charAt(i)));            }            //如果没有重复,那么就i向前,j不动,用i-j+1来记录长度            max = Math.max(max,i-j+1);            map.put(s.charAt(i),i+1);                    }        return max;    }}


阅读全文
0 0