记录了初步解题思路 以及本地实现代码;并不一定为最优 也希望大家能一起探讨 一起进步
目录
12/26 1759. 统计同构子字符串的数目
对于连续k个相同字符的字符串可以提供1+2+…+k个同构字符串
从头遍历
def countHomogenous(s):
"""
:type s: str
:rtype: int
"""
MOD = 10**9+7
num = 0
ans = 0
cur = ""
for c in s:
if c==cur:
num+=1
else:
cur = c
num = 1
ans = (ans+num)%MOD
return ans
12/27 2027. 转换字符串的最少操作次数
从头遍历 遇到X 将跳过其后面两个
def minimumMoves(s):
"""
:type s: str
:rtype: int
"""
ans = 0
n = len(s)
i = 0
while i<n:
if s[i]=="X":
ans +=1
i += 2
i+=1
return ans
12/28 1750. 删除字符串两端相同字符后的最短长度
双指针 分别检查当前头尾是否相同
def minimumLength(s):
"""
:type s: str
:rtype: int
"""
n = len(s)
l,r = 0,len(s)-1
while l<r:
if s[l]==s[r]:
while l+1<n and s[l]==s[l+1] and l<r:
l+=1
while r>0 and s[r]==s[r-1] and l<r:
r-=1
if l>r:
break
if l==r:
l+=1
break
l+=1
r-=1
else:
break
return r-l+1
12/29 2032. 至少在两个数组中出现的值
两两交集 再取并集
def twoOutOfThree(nums1, nums2, nums3):
"""
:type nums1: List[int]
:type nums2: List[int]
:type nums3: List[int]
:rtype: List[int]
"""
s1 = set(nums1)
s2 = set(nums2)
s3 = set(nums3)
return list((s1&s2)|(s1&s3)|(s2&s3))
12/30 855. 考场就座
s数组记录当前已经坐了的位置
一次遍历判断相邻两个位子间的空位
import bisect
class ExamRoom(object):
def __init__(self, n):
"""
:type n: int
"""
self.n = n
self.s = []
def seat(self):
"""
:rtype: int
"""
if len(self.s)==0:
st = 0
else:
dis,st = self.s[0],0
for i,s in enumerate(self.s):
if i:
prev = self.s[i-1]
d = (s-prev)//2
if d>dis:
dis,st = d,prev+d
d = self.n-1-self.s[-1]
if d>dis:
st = self.n-1
bisect.insort(self.s,st)
return st
def leave(self, p):
"""
:type p: int
:rtype: None
"""
self.s.remove(p)
12/31 2037. 使每位学生都有座位的最少移动次数
要使得移动次数最少 将两数组排序
第i个学生坐到第i个位置
def minMovesToSeat(seats, students):
"""
:type seats: List[int]
:type students: List[int]
:rtype: int
"""
ans = 0
seats.sort()
students.sort()
for i,ind in enumerate(students):
ans += abs(ind-seats[i])
return ans
1/1 2351. 第一个出现两次的字母
从头依序遍历 集合存储出现过的字母
def repeatedCharacter(s):
"""
:type s: str
:rtype: str
"""
mem = set()
for c in s:
if c in mem:
return c
mem.add(c)