leetcode-----3. 无重复字符的最长子串

思路

  定义两个指针i和j,表示当前扫描的字串为i到j区间。使用HashMap对其进行存储。
  寻找当前字母出现的上一次位置,比较得到最大值。

代码

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int ans = 0;
        int n = s.length();
        Map<Character, Integer> map = new HashMap<>();

        for (int i = 0, j = 0; j < n; ++j) {
            char alpha = s.charAt(j);
            if (map.containsKey(alpha)) {
                i = Math.max(map.get(alpha), i);
            }
            ans = Math.max(ans, j - i + 1);
            map.put(alpha, j + 1);
        }
        return ans;
    }
}
posted @ 2020-06-01 21:22  景云ⁿ  阅读(59)  评论(0编辑  收藏  举报