Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Longest Substring Without Repeating Characters

Posted on January 26, 2018July 26, 2020 by braindenny

Longest Substring Without Repeating Characters



Similar Problems:

  • LeetCode: Substring with Concatenation of All Words
  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #slidingwindow, #atmostkdistinct

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.

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


// https://code.dennyzhang.com/longest-substring-without-repeating-characters
// Basic Ideas: Sliding window
//
// Complexity: Time O(n), Space O(1)
func lengthOfLongestSubstring(s string) int {
    l := make([]int, 128)
    res := 0
    // s[i...j]
    i := 0
    for j, v := range s {
        index := byte(v)
        l[index]++
        for l[index] > 1 {
            l[s[i]]--
            i++
        }
        if j-i+1 > res {
            res = j-i+1
        }
    }
    return res
}
// https://code.dennyzhang.com/longest-substring-without-repeating-characters
// Basic Ideas: Sliding window
//
// Complexity: Time O(n), Space O(n)
func lengthOfLongestSubstring(s string) int {
    m := map[byte]int{}
    res := 0
    // s[i...j]
    i := 0
    for j, _ := range s {
        v := byte(s[j])
        m[v]++
        for m[v]>1 {
            m[s[i]]--
            i++
        }
        if j-i+1 > res {
            res = j-i+1
        }
    }
    return res
}
linkedin
github
slack

Post Views: 3
Posted in MediumTagged #slidingwindow, atmostkdistinct

Post navigation

LeetCode: Basic Calculator III
LeetCode: Clone Graph

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.