[LeetCode] 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.


</br>

Solution

Though the basic brute force way to lay out all the possible substrings to each determine whether it is without repeating characters may seem straightforward, this method is low time-efficiency and will result in TLE.

Hence we have to avoid using unnecessary loop and try to check the repeating characters while iterating all the possible substrings.

Therefore, we can consider establishing a slider to control which substring to choose. For the slider [ i, j ], if this substring does not contain repeating characters, then we increase the value of j as if we have broaden the slider in order to examine the next substring. On the contrary, if the substring does contain repeating substring, then we have to increase the value of i as if we slide the entire slider forward.

The code is shown as below.

Java

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        
        int maxLength = 0, i = 0, j = 0;
        
        Set<Character> set = new HashSet<>();
        
        while(i < s.length() && j < s.length()){
            
            if (set.contains(s.charAt(j))){
                set.clear();
                i++;
                j = i;
            }
            else{
                set.add(s.charAt(j));
                maxLength = Math.max(maxLength, j-i+1);
                j++;
            }
        }
        return maxLength;
    }
}

One more thing, whether to use HashSet or HashMap can also makes a difference for their different time efficiency. Using HashMap in the code above can result in TLE, while switching to HashSet can avoid this problem.
</br>

Complexity Analysis

Time Complexity: O(n^2).
Space Complexity: O(n).
</br>

Further Development

Even though the code can be accepted, the efficiency can be further improved. We can actually optimize the code to check the substring in one pass.

When there is a duplicate in the current substring, instead of increasing i by one, we can actually skip all the characters before the next same duplicate letters.

For example, for string "dvdf", when encountering the second d, instead of increasing i by one, we can skip to the characters before the second "d".

Therefore, we can use the HashMap to record the position of the letters to determine the exact value i should increase.

The optimized code is shown below.

Java

public class Solution {
    public int lengthOfLongestSubstring(String s) {

        int maxLength = 0;

        Map<Character, Integer> map = new HashMap<>(); // current index of character

        for (int j = 0, i = 0; j < s.length(); j++) {
            if (map.containsKey(s.charAt(j))) {
                i = Math.max(map.get(s.charAt(j)), i);
            }
            maxLength = Math.max(maxLength, j - i + 1);
            map.put(s.charAt(j), j + 1);
        }
        return maxLength;
    }
}

</br>

Complexity Analysis

Time Complexity: O(n).
Space Complexity: O(n).
</br>
</br>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市赠幕,隨后出現(xiàn)的幾起案子镰踏,更是在濱河造成了極大的恐慌咖杂,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,198評(píng)論 6 514
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件吼具,死亡現(xiàn)場(chǎng)離奇詭異奕翔,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)撒妈,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,334評(píng)論 3 398
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)排监,“玉大人狰右,你說(shuō)我怎么就攤上這事∮叽玻” “怎么了棋蚌?”我有些...
    開封第一講書人閱讀 167,643評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)挨队。 經(jīng)常有香客問我谷暮,道長(zhǎng),這世上最難降的妖魔是什么瞒瘸? 我笑而不...
    開封第一講書人閱讀 59,495評(píng)論 1 296
  • 正文 為了忘掉前任坷备,我火速辦了婚禮,結(jié)果婚禮上情臭,老公的妹妹穿的比我還像新娘省撑。我一直安慰自己赌蔑,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,502評(píng)論 6 397
  • 文/花漫 我一把揭開白布竟秫。 她就那樣靜靜地躺著娃惯,像睡著了一般。 火紅的嫁衣襯著肌膚如雪肥败。 梳的紋絲不亂的頭發(fā)上趾浅,一...
    開封第一講書人閱讀 52,156評(píng)論 1 308
  • 那天,我揣著相機(jī)與錄音馒稍,去河邊找鬼皿哨。 笑死,一個(gè)胖子當(dāng)著我的面吹牛纽谒,可吹牛的內(nèi)容都是我干的证膨。 我是一名探鬼主播,決...
    沈念sama閱讀 40,743評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼鼓黔,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼央勒!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起澳化,我...
    開封第一講書人閱讀 39,659評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤崔步,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后缎谷,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體井濒,經(jīng)...
    沈念sama閱讀 46,200評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,282評(píng)論 3 340
  • 正文 我和宋清朗相戀三年慎陵,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了眼虱。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,424評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡席纽,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出撞蚕,到底是詐尸還是另有隱情润梯,我是刑警寧澤,帶...
    沈念sama閱讀 36,107評(píng)論 5 349
  • 正文 年R本政府宣布甥厦,位于F島的核電站纺铭,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏刀疙。R本人自食惡果不足惜舶赔,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,789評(píng)論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望谦秧。 院中可真熱鬧竟纳,春花似錦撵溃、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,264評(píng)論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至桶略,卻和暖如春语淘,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背际歼。 一陣腳步聲響...
    開封第一講書人閱讀 33,390評(píng)論 1 271
  • 我被黑心中介騙來(lái)泰國(guó)打工惶翻, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人鹅心。 一個(gè)月前我還...
    沈念sama閱讀 48,798評(píng)論 3 376
  • 正文 我出身青樓吕粗,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親巴帮。 傳聞我的和親對(duì)象是個(gè)殘疾皇子溯泣,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,435評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容

  • Problem Given a string, find the length of the longest su...
    做夢(mèng)枯島醒閱讀 234評(píng)論 0 0
  • 文章為csslint中文版譯文,點(diǎn)擊原文可查看英文版榕茧,如遇到翻譯錯(cuò)誤或錯(cuò)別字啥的垃沦,請(qǐng)留言指出~ 譯文內(nèi)容不定期更新...
    唐小律閱讀 514評(píng)論 0 0
  • 上午忙碌的工作 下午探訪老上海 上海電影博物館 重慶公寓 思南公館 都是去過(guò)的地方 也沒啥好說(shuō)的
    角落蜷縮閱讀 153評(píng)論 0 0
  • 那一年,那一次深浮,時(shí)光流走蜻拨,你是否愛我如初池充?你不愛我,我不怪你 說(shuō)起曾經(jīng)總是有些傷感缎讼,有些甜蜜收夸,但我們回不去了。 故...
    暖楠垂閱讀 271評(píng)論 1 2
  • 我不知道 我是誰(shuí) 我不知道 我該做什么 我不知道 過(guò)去 現(xiàn)在 將來(lái) 會(huì)怎么樣 會(huì)發(fā)生什么 我總覺得 時(shí)間很長(zhǎng) 長(zhǎng)到...
    19days閱讀 153評(píng)論 0 1