3. Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: 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.
找最长的不重复子串长度,可以用字典存储下每个字符出现的位置,当出现相同字符的时候,就可以得到两个相同字符之间的长度;
设置一个start的位置,为了防止"abba"的情况,可以保证每次cur_max更新的时候是从最后一个被比较过的字符的位置后面开始的。
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) == 0:
return 0
if len(s) == 1:
return 1
tmp_dict = {}
start = 0
res = 0
cur_max = 0
for idx, char in enumerate(s):
if char in tmp_dict and tmp_dict[char] >= start:
res = max(res, cur_max)
cur_max = idx - tmp_dict[char]
start = tmp_dict[char] + 1
else:
cur_max += 1
tmp_dict[char] = idx
return max(res, cur_max)
30. Substring with Concatenation of All Words
You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.
Example 1:
Input:
s = "barfoothefoobarman",
words = ["foo","bar"]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.
Example 2:
Input:
s = "wordgoodgoodgoodbestword",
words = ["word","good","best","word"]
Output: []
题干中提到了每个单词都是等长的,所以可以对s中每lw个字符判断一下是否在words的字典里面
判断concatenation的时候就可以用while循环,两个break的条件:
第一个是使用tmp字典存储下每个单词出现的次数,如果substring中出现的单词不止一次就退出;
第二个是如果某单词不存在于字典中就退出。
注意整体上循环的次数应该是ls + 1 - lw*num次,也就是最多能有多少个substring的起始位置
class Solution(object):
def findSubstring(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: List[int]
"""
if s=="" or words == []:
return []
dic = {}
num = len(words)
for i in words:
if i not in dic:
dic[i] = 1
else:
dic[i] += 1
tmp = words[0]
lw = len(tmp)
ls = len(s)
res = []
for i in range(ls + 1 - lw*num):
tmp = {}
j=0
while j < num:
w = s[i+j*lw:i+(j+1)*lw]
if w not in dic:
break
if w not in tmp:
tmp[w] = 1
else:
tmp[w] += 1
if tmp[w] > dic[w]:
break
j+=1
if j == num:
res.append(i)
return res