首页 > 其他 > 详细

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

时间:2020-06-01 22:42:46      阅读:49      评论:0      收藏:0      [点我收藏+]

思路

  定义两个指针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;
    }
}

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

原文:https://www.cnblogs.com/clown9804/p/13027530.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!