最长不含重复字符的子字符串

47 阅读1分钟

题目:leetcode-cn.com/problems/zu…

使用Hash表+双指针的做法
遇到相同的值,就从hash表中取出该值前一次出现的位置,做一次比较,保证值是最大的。

public static int lengthOfLongestSubstring(String s) {
        //使用hash表来判断
       Map<Character,Integer> map = new HashMap<Character, Integer>();
       int res = 0,j = -1;

       //循环遍历字符串
       for(int i = 0;i < s.length(); i++){
           //判断相同的值
            if(map.containsKey(s.charAt(i)))
                //更新j,取最大的j
                j = Math.max(j,map.get(s.charAt(i)));
            //把字符写入hash表
           map.put(s.charAt(i),i);
           //取res的最大值
           res = Math.max(res ,i - j );
       }
       return res;
    }