[英]How can I loop through a python list stopping at every element
I am trying to solve this Leetcode problem, without using Sets我正在尝试解决这个 Leetcode 问题,而不使用 Sets
https://leetcode.com/problems/longest-substring-without-repeating-characters/ https://leetcode.com/problems/longest-substring-without-repeating-characters/
The way im tackling it is by stopping at every element in the list and going one element right until i find a duplicate, store that as the longest subset without duplication and continuing with the next element to do it again.我解决它的方法是在列表中的每个元素处停止并向右移动一个元素,直到找到重复项,将其存储为最长的子集而不重复,然后继续下一个元素再次执行。
I'm stuck because i cant find a way to iterate the whole list at every element我被卡住了,因为我找不到在每个元素处迭代整个列表的方法
Below is what i have so far以下是我到目前为止所拥有的
def lengthOfLongestSubstring(self, s):
mylist = list(s)
mylist2 = list(s)
final_res = []
res = []
for i in mylist2:
for char in mylist:
if char in res:
res=[]
break
else:
res.append(char)
if len(res) > len(final_res):
final_res = res
return final_res
If your goal is primarily to avoid using set
(or dict
), you can use a solution based on buckets for the full range of possible characters ("English letters, digits, symbols and spaces", which have numeric codes in the range 0-127):如果您的目标主要是避免使用set
(或dict
),您可以使用基于桶的解决方案来处理所有可能的字符(“英文字母、数字、符号和空格”,其数字代码范围为 0- 127):
class Solution(object):
def lengthOfLongestSubstring(self, s):
'''
at a given index i with char c,
if the value for c in the list of buckets b
has a value (index of most recent sighting) > start,
update start to be that value + 1
otherwise update res to be max(res, i - start + 1)
update the value for c in b to be i
'''
res, start, b = 0, 0, [-1]*128
for i, c in enumerate(s):
k = ord(c)
if b[k] >= start:
start = b[k] + 1
else:
res = max(res, i - start + 1)
b[k] = i
return res
The call to ord()
allows integer indexing of the bucketed list b
.对ord()
的调用允许对桶列表b
进行整数索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.