3. Longest Substring Without Repeating Characters

  • Source : Link
  • Author : Han
  • Date : 2022-01-11

Problems

Given a string s, find the length of the longest substring without repeating characters.

Example 1:

1
2
3
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Example 2:

1
2
3
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

1
2
3
4
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import kotlin.math.max

class Solution {
    fun lengthOfLongestSubstring(s: String): Int {
        if(s.isEmpty()) return 0
        var remove = 0; var current = 0; var max = Int.MIN_VALUE
        val set = hashSetOf<Char>()
        while(current < s.length){
            if(s[current] in set){
                this.getMax(max, remove, current).also { max = it }
                while(remove < s.length && set.contains(s[current])) set.remove(s[remove++])
            }
            set.add(s[current++])
        }

        return this.getMax(max, remove, current).also { max = it }
    }
    private fun getMax(max: Int, start: Int, current: Int) = max(max, current - start)
}