Skip to content

Latest commit

 

History

History
84 lines (58 loc) · 3.19 KB

File metadata and controls

84 lines (58 loc) · 3.19 KB

Longest Substring Without Repeating Characters

So, this problem is available on LeetCode.

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

Pointers

You'll probably want to know about string manipulation

BAM! It's only 5 minutes of reading so totally worth it to get some basic familiarity. Oh, also DOUBLE BAM!. That's all the functions you get on a string.

I'll give you some gist though:

a_string = 'Python is super duper fun and cool'
# You can find when something occurs in a string
first_s = a_string.index('s')
second_s = a_string.index('s', first_s + 1)
print(f"The first 's' occurs at index {first_s} and the second at {second_s}")

# You can read a letter from a string based on an index
whats_after_the_second_s = a_string[second_s + 1]
print(f"whats_after_the_second_s='{whats_after_the_second_s}'")
# P.S. an easier way to do the above is:
print(f"{whats_after_the_second_s=}")
# Now we're cool!

# You can 'slice' a string too
# i.e. you don't want the whole thing, you only want a little slice
a_substring = a_string[10:21]
print(f"I got a cool substring: '{a_substring}'")

That's probably about all you need to know right now.

You can use a set

In Python a set is an unordered collection of data where each element is unique. Read all about it!
Sets offer a very quick test of membership as each object is hashed and as such membership can be checked in linear time.

empty_set = set()
busy_set = {1, 2, 3, 'monkey'}  # This is similar to dictionary declaration but don't get mixed up

empty_set.add(2)  # We can add to a set
empty_set.add(6)

if 6 in empty_set:
    print("It's in there!")


# Sets have a nice mathematical notation that can perform quite powerful checks

common = empty_set & busy_set
print(f"Theses sets have this stuff in common: {common}")

one_or_the_other = empty_set ^ busy_set
print(f"These are found in one but not the other: {one_or_the_other}")

Read about how you can use sets

You could also use a dictionary

In Python a "dictionary" is our key-value pair, they're almost exactly the same as sets but they have a value attached to each element. Read all about it!

empty_dict = {}
busy_dict = {'a': 1, 'funny': 'not you', 2: 'b'}

# We can add to a dict
empty_dict['new key'] = 'new value'
empty_dict['funny'] = 'Monty Python'  # If either of these keys already exist then we will overwrite the value like this

# We can check if a key exists in the dictionary
if 'funny' in empty_dict:
    print("There's something funny in here!")
    # We can access the value too
    funny_value = empty_dict['funny']  # Raises an exception is not present
    print(f"The funny thing is: {funny_value}")

Read about how you can use dictionaries