Hello readers! It’s really important for me to continue my practice and learning. Every week, I block off 30 minutes, set a timer and choose a challenge from leetcode. This helps me keep my skills sharp, see how other devs all over the planet would solve these problems, and take some leisure time to problem solve and be creative. Being able to see other solutions expands my mind for solving future problems in a clever and efficient way. Today, the problem set focuses on Python.
Given a string
s, find the length of the longest substring without repeating characters.
Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3.
Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1.
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.
0 <= s.length <= 5 * 104
sconsists of English letters, digits, symbols and spaces.
class Solution(object): def lengthOfLongestSubstring(self, s): substring =  #initialize substring array to empty longest = 0 #set longest value to 0 for i in s: if (i not in substring): # check if letter in s is in substring, if not, then... substring.append(i) # add the letter to the substring array if (len(substring) > longest): #continously check to see if substring is greater than longest longest = len(substring) #if it is, update longest to the new value else: #if i is in substring, it means we have found a duplicate substring = substring[substring.index(i)+1:] #get everything to the right of the original dupe substring.append(i) #we still want to add the letter to the substring return longest #return the longest int value
All solutions are also now on my GitHub profile if you want to check out all of the coding challenges I’ve completed so far!
All credit to problem sets goes to Leetcode