3. Longest Substring Without Repeating Characters

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.

Solution:
基本想法:维护一个hashmap,其中字符为key,位置为value,同时维护两个指针用于计算最长子串。右指针扫描,同时更新hashmap。如果某个字符已经在hashmap里面,将左指针移动到上一次发现该字符的右一位。注意两个指针可以同时移动。

class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s.length() == 0)    return 0;
        Map<Character, Integer> map = new HashMap<>();
        int max = 0;
        for (int i = 0, j = 0; i < s.length(); ++i){
            if (map.containsKey(s.charAt(i))){
                j = Math.max(j, map.get(s.charAt(i))+1);
            }
            map.put(s.charAt(i), i);
            max = Math.max(max, i-j+1);
        }
        return max;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 很久以前,我便想写一写我的母亲,但总觉得手中的笔很重,无从下手。促使我今天动笔的,却是近几个月来,母亲的听力日渐减...
    聆听万籁阅读 342评论 6 10
  • 从2016年开始零基础摸索画水彩,一直到现在,记录下自己的小快乐。
    仓央梅朵阅读 477评论 1 1
  • 曾经 在枝头光鲜 母亲把孩子举过头顶 一阵秋风吹来 母亲放手,孩子独行 从天上降临凡间 尘埃,尘埃,尘埃 光鲜一夜...
    张一冉阅读 182评论 0 0
  • 畅所欲言那是曾经 当把奢望说出口 又有几分悔意 本不想让彼此回到那个沉默的当初 不知是哪来的勇气 想要一句来自寒冬...
    萧谷南溪微辞阅读 132评论 2 8