3. Longest Substring Without Repeating Characters

Description:

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:

Approach 1:Brute Force [Time Limit Exeeded]

A 2-layer loop,i and j denote the start and the end of the substring. A HashSet is used to record the characters in the substring. Every time in the inner loop we check if s[j] is in the set. Once s[j] is already in the set, we break the inner loop to begin a new outer loop, or else we put it into the set and update the max.

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int max = 0;
        for (int i = 0; i < s.length(); i++) {
            HashSet<Character> set = new HashSet<>();
            for (int j = i; j < s.length(); j++) {
                if(!set.contains(s.charAt(j))) {
                    set.add(new Character(s.charAt(j)));
                    max = Math.max(max, set.size());
                } else {
                    break;
                }
                
            }
        }
        return max;
    }
}

Approach 2: Using HashMap with time complexity O(n)

We can use a HashMap to record the position in the substring, which would allow i straightly go behind the same character of s[j] in the substring.

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int i = 0;
        int n = s.length();
        int max = 0;
        HashMap<Character, Integer> map = new HashMap<>();
        for(int j = 0; j < n; j++) {
            if(map.containsKey(s.charAt(j))) {
                i = Math.max(i, map.get(s.charAt(j))+1);  // i goes behind the the same character of s[j] in the substring
            }
            map.put(s.charAt(j), j); // every time we need to record the position
            max = Math.max(max, j-i+1);

        }
        return max;
    }
}

Detailed should be paid attention to as followings:

  • i can only go forward so when update i, we do not need to change its value if the the value (index) of s.charAt(j) in the map is lower than i (which means the value (index) is out of the current substring).
  • map must be updated every time we enter the loop. I have made the mistake that if the map contains s[j] it will not be updated. After thinking for a while, I figured out that if the map contains s[j], i(the start of the substring) will be update and the substring (s[i...j]) only contains one s[j]'s character. So map must be updated to record the new position of s[j].

Approach 3: Using an array to replace HashMap with time complexity O(n)

Since we know that there are no more than 128 kinds of characters in ASCII, we could use an array to mimic the HashMap

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int[] c = new int[128];
        int max = 0;
        for(int i = 0, j = 0; j < s.length(); j++) {
            i = Math.max(i, c[s.charAt(j)]);
            c[s.charAt(j)] = j+1; // j+1 indicates the position right behind s[j]
            max = Math.max(max, j-i+1);
        }
        return max;
    }
}

However, I cannot convert HashMap to array. Details are as followings:
The most significant difference is when update the c array, we use j+1 to record the position, which would cooperate with the previous line i = Math.max(i, c[s.charAt(j)]);. j+1 indicates the position when i need to be updated. But why don't we let it just be j and make the previous line as i = Math.max(i, c[s.charAt(j)]+1);. Here is the issue:
When using HashMap, we update i if and only if the map contains s[j], but when using array, we update i every time we enter in the loop, which would cause a problem when the character is first appear in the string.
So imagine the situation that the string itself is the wanted string, but i will be updated to 1 because all the entry value of the array c is 0, and c[s.charAt(j)]+1 will be 1. We can solve the problem in 2 ways:

  • If we add a if clause if (c[s.charAt(j)] != 0) to decide whether to update i, then the i = Math.max(i, c[s.charAt(j)]+1); will work.
  • Additionally, we can also let the all the initial entry value of array c to be -1, which will also well handle the issue.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,324评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,303评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,192评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,555评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,569评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,566评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,927评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,583评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,827评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,590评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,669评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,365评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,941评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,928评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,159评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,880评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,399评论 2 342

推荐阅读更多精彩内容

  • 长大后不知为什么总是讨厌一个人。总感觉身边少一种情切感,一种安全感。好不容易考上了大学,总以为会有很多很多的朋友,...
    陀罗阅读 573评论 5 1
  • 为什么要写作尼?冥冥之中感受到了上天的感召?还是有一颗不走寻常路的文艺心哪?不,都不是!写作最重要的还是指导生活,...
    shandow阅读 188评论 0 1
  • 龚琳娜这个名字,我们都不陌生。2010年她凭借神曲《忐忑》迅速走红。这个曲子之所以在众多的网络歌曲中脱颖而出,一方...
    老苹果2阅读 638评论 1 2
  • 烟柳画桥 曲径窄道 一池碧水菱荇少 白鸟翔云俏 黑蝶戏花娇 渚上垂钓者 绿杨阴里 不闻蝉声噪 尘世喧嚣 浮生烦扰 ...
    冷眼加白眼阅读 120评论 1 1