inputs
stringlengths 50
14k
| targets
stringlengths 4
655k
|
|---|---|
Given an integer array bloomDay, an integer m and an integer k.
We need to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.
Example 1:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 1
Output: 3
Explanation: Let's see what happened in the first three days. x means flower bloomed and _ means flower didn't bloom in the garden.
We need 3 bouquets each should contain 1 flower.
After day 1: [x, _, _, _, _] // we can only make one bouquet.
After day 2: [x, _, _, _, x] // we can only make two bouquets.
After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.
Example 2:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 2
Output: -1
Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.
Example 3:
Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3
Output: 12
Explanation: We need 2 bouquets each should have 3 flowers.
Here's the garden after the 7 and 12 days:
After day 7: [x, x, x, x, _, x, x]
We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.
After day 12: [x, x, x, x, x, x, x]
It is obvious that we can make two bouquets in different ways.
Example 4:
Input: bloomDay = [1000000000,1000000000], m = 1, k = 1
Output: 1000000000
Explanation: You need to wait 1000000000 days to have a flower ready for a bouquet.
Example 5:
Input: bloomDay = [1,10,2,9,3,8,4,7,5,6], m = 4, k = 2
Output: 9
Constraints:
bloomDay.length == n
1 <= n <= 10^5
1 <= bloomDay[i] <= 10^9
1 <= m <= 10^6
1 <= k <= n
|
class Solution:
def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
if k*m > len(bloomDay):
return -1
unique_bloom_days = sorted(set(bloomDay))
lo = 0
hi = len(unique_bloom_days)-1
if hi == 0:
return unique_bloom_days[0]
while True:
curr_idx = int((lo+hi)/2)
if curr_idx == lo:
idx = curr_idx
curr_day = unique_bloom_days[curr_idx]
# check if the condition is satisfiable
bouquet = 0
curr = 0
for i in range(len(bloomDay)):
if bloomDay[i] <= curr_day:
curr += 1
if curr >= k:
bouquet += 1
curr = 0
else:
curr = 0
if bouquet < m: # not enough
if curr_idx == lo:
idx = lo+1
break
else:
lo = curr_idx
else: # enough
hi = curr_idx
if hi == lo:
idx = hi
break
return unique_bloom_days[idx]
|
Given an integer array bloomDay, an integer m and an integer k.
We need to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.
Example 1:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 1
Output: 3
Explanation: Let's see what happened in the first three days. x means flower bloomed and _ means flower didn't bloom in the garden.
We need 3 bouquets each should contain 1 flower.
After day 1: [x, _, _, _, _] // we can only make one bouquet.
After day 2: [x, _, _, _, x] // we can only make two bouquets.
After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.
Example 2:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 2
Output: -1
Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.
Example 3:
Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3
Output: 12
Explanation: We need 2 bouquets each should have 3 flowers.
Here's the garden after the 7 and 12 days:
After day 7: [x, x, x, x, _, x, x]
We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.
After day 12: [x, x, x, x, x, x, x]
It is obvious that we can make two bouquets in different ways.
Example 4:
Input: bloomDay = [1000000000,1000000000], m = 1, k = 1
Output: 1000000000
Explanation: You need to wait 1000000000 days to have a flower ready for a bouquet.
Example 5:
Input: bloomDay = [1,10,2,9,3,8,4,7,5,6], m = 4, k = 2
Output: 9
Constraints:
bloomDay.length == n
1 <= n <= 10^5
1 <= bloomDay[i] <= 10^9
1 <= m <= 10^6
1 <= k <= n
|
class Solution:
def minDays(self, A: List[int], m: int, k: int) -> int:
if m * k > len(A): return -1
left, right = 1, max(A)
while left < right:
mid = (left + right) >> 1
flow = bouq = 0
for a in A:
flow = 0 if a > mid else flow + 1
if flow >= k:
flow = 0
bouq += 1
if bouq == m: break
if bouq == m:
right = mid
else:
left = mid + 1
return left
|
Given an integer array bloomDay, an integer m and an integer k.
We need to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.
Example 1:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 1
Output: 3
Explanation: Let's see what happened in the first three days. x means flower bloomed and _ means flower didn't bloom in the garden.
We need 3 bouquets each should contain 1 flower.
After day 1: [x, _, _, _, _] // we can only make one bouquet.
After day 2: [x, _, _, _, x] // we can only make two bouquets.
After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.
Example 2:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 2
Output: -1
Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.
Example 3:
Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3
Output: 12
Explanation: We need 2 bouquets each should have 3 flowers.
Here's the garden after the 7 and 12 days:
After day 7: [x, x, x, x, _, x, x]
We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.
After day 12: [x, x, x, x, x, x, x]
It is obvious that we can make two bouquets in different ways.
Example 4:
Input: bloomDay = [1000000000,1000000000], m = 1, k = 1
Output: 1000000000
Explanation: You need to wait 1000000000 days to have a flower ready for a bouquet.
Example 5:
Input: bloomDay = [1,10,2,9,3,8,4,7,5,6], m = 4, k = 2
Output: 9
Constraints:
bloomDay.length == n
1 <= n <= 10^5
1 <= bloomDay[i] <= 10^9
1 <= m <= 10^6
1 <= k <= n
|
class Solution:
def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
if bloomDay == [] or m * k == 0 or len(bloomDay) < m * k:
return -1
left, right = 1, max(bloomDay)
while left < right:
mid = left + (right - left) // 2
if self.getPossibleBouquetNum(bloomDay, k, mid) >= m:
right = mid
else:
left = mid + 1
return left
def getPossibleBouquetNum(self, bloomDay: List[int], k: int, day_threshold: int) -> int:
bloom_count = 0
bouquet_count = 0
for day in bloomDay:
if day <= day_threshold:
bloom_count += 1
else:
bouquet_count += bloom_count // k
bloom_count = 0
bouquet_count += bloom_count // k
return bouquet_count
|
Given an integer array bloomDay, an integer m and an integer k.
We need to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.
Example 1:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 1
Output: 3
Explanation: Let's see what happened in the first three days. x means flower bloomed and _ means flower didn't bloom in the garden.
We need 3 bouquets each should contain 1 flower.
After day 1: [x, _, _, _, _] // we can only make one bouquet.
After day 2: [x, _, _, _, x] // we can only make two bouquets.
After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.
Example 2:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 2
Output: -1
Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.
Example 3:
Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3
Output: 12
Explanation: We need 2 bouquets each should have 3 flowers.
Here's the garden after the 7 and 12 days:
After day 7: [x, x, x, x, _, x, x]
We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.
After day 12: [x, x, x, x, x, x, x]
It is obvious that we can make two bouquets in different ways.
Example 4:
Input: bloomDay = [1000000000,1000000000], m = 1, k = 1
Output: 1000000000
Explanation: You need to wait 1000000000 days to have a flower ready for a bouquet.
Example 5:
Input: bloomDay = [1,10,2,9,3,8,4,7,5,6], m = 4, k = 2
Output: 9
Constraints:
bloomDay.length == n
1 <= n <= 10^5
1 <= bloomDay[i] <= 10^9
1 <= m <= 10^6
1 <= k <= n
|
class Solution:
def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
if m * k > len(bloomDay):
return -1
def bouqets(d):
res, c = 0, 0
for n in bloomDay:
c = 0 if n > d else c + 1
if c == k:
res, c = res + 1, 0
return res
days = sorted(set(bloomDay))
lo, hi = 0, len(days)-1
while lo < hi:
mid = (lo + hi) // 2
if bouqets(days[mid]) < m:
lo = mid + 1
else:
hi = mid
return days[hi] if days[hi] >= m else -1
|
Given an integer array bloomDay, an integer m and an integer k.
We need to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.
Example 1:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 1
Output: 3
Explanation: Let's see what happened in the first three days. x means flower bloomed and _ means flower didn't bloom in the garden.
We need 3 bouquets each should contain 1 flower.
After day 1: [x, _, _, _, _] // we can only make one bouquet.
After day 2: [x, _, _, _, x] // we can only make two bouquets.
After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.
Example 2:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 2
Output: -1
Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.
Example 3:
Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3
Output: 12
Explanation: We need 2 bouquets each should have 3 flowers.
Here's the garden after the 7 and 12 days:
After day 7: [x, x, x, x, _, x, x]
We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.
After day 12: [x, x, x, x, x, x, x]
It is obvious that we can make two bouquets in different ways.
Example 4:
Input: bloomDay = [1000000000,1000000000], m = 1, k = 1
Output: 1000000000
Explanation: You need to wait 1000000000 days to have a flower ready for a bouquet.
Example 5:
Input: bloomDay = [1,10,2,9,3,8,4,7,5,6], m = 4, k = 2
Output: 9
Constraints:
bloomDay.length == n
1 <= n <= 10^5
1 <= bloomDay[i] <= 10^9
1 <= m <= 10^6
1 <= k <= n
|
class Solution:
def make_bouquets(self, A, day, k):
cnt, consec = 0, 0
for i in A:
if day >= i:
consec += 1
else:
consec = 0
if consec == k:
cnt += 1
consec = 0
return cnt
def minDays(self, A, m, k):
l, r = min(A), max(A)
print(f'{l=} | {r=}')
while r > l:
mid = (l+r) // 2
if self.make_bouquets(A, mid, k) >= m:
r = mid
else:
l = mid + 1
print(f'{l=} | {r=}')
if self.make_bouquets(A, l, k) >= m:
return l
else: return -1
|
Given an integer array bloomDay, an integer m and an integer k.
We need to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.
Example 1:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 1
Output: 3
Explanation: Let's see what happened in the first three days. x means flower bloomed and _ means flower didn't bloom in the garden.
We need 3 bouquets each should contain 1 flower.
After day 1: [x, _, _, _, _] // we can only make one bouquet.
After day 2: [x, _, _, _, x] // we can only make two bouquets.
After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.
Example 2:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 2
Output: -1
Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.
Example 3:
Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3
Output: 12
Explanation: We need 2 bouquets each should have 3 flowers.
Here's the garden after the 7 and 12 days:
After day 7: [x, x, x, x, _, x, x]
We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.
After day 12: [x, x, x, x, x, x, x]
It is obvious that we can make two bouquets in different ways.
Example 4:
Input: bloomDay = [1000000000,1000000000], m = 1, k = 1
Output: 1000000000
Explanation: You need to wait 1000000000 days to have a flower ready for a bouquet.
Example 5:
Input: bloomDay = [1,10,2,9,3,8,4,7,5,6], m = 4, k = 2
Output: 9
Constraints:
bloomDay.length == n
1 <= n <= 10^5
1 <= bloomDay[i] <= 10^9
1 <= m <= 10^6
1 <= k <= n
|
class Solution:
def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
if (len(bloomDay) < m * k):
return -1
sorted_bloomDay = sorted(set(bloomDay))
left = 1
right = len(sorted_bloomDay)
ret = -1
while (left <= right):
middle = (left + right) // 2 - 1
bouquets_left = m
flowers_left = k
search_right = True
for i in range(len(bloomDay)):
if (bloomDay[i] <= sorted_bloomDay[middle]):
flowers_left -= 1
if (flowers_left == 0):
bouquets_left -= 1
if (bouquets_left == 0):
ret = sorted_bloomDay[middle]
search_right = False
break
else:
flowers_left = k
else:
flowers_left = k
if (search_right):
left = middle + 2
else:
right = middle
return ret
|
Given an integer array bloomDay, an integer m and an integer k.
We need to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.
Example 1:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 1
Output: 3
Explanation: Let's see what happened in the first three days. x means flower bloomed and _ means flower didn't bloom in the garden.
We need 3 bouquets each should contain 1 flower.
After day 1: [x, _, _, _, _] // we can only make one bouquet.
After day 2: [x, _, _, _, x] // we can only make two bouquets.
After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.
Example 2:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 2
Output: -1
Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.
Example 3:
Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3
Output: 12
Explanation: We need 2 bouquets each should have 3 flowers.
Here's the garden after the 7 and 12 days:
After day 7: [x, x, x, x, _, x, x]
We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.
After day 12: [x, x, x, x, x, x, x]
It is obvious that we can make two bouquets in different ways.
Example 4:
Input: bloomDay = [1000000000,1000000000], m = 1, k = 1
Output: 1000000000
Explanation: You need to wait 1000000000 days to have a flower ready for a bouquet.
Example 5:
Input: bloomDay = [1,10,2,9,3,8,4,7,5,6], m = 4, k = 2
Output: 9
Constraints:
bloomDay.length == n
1 <= n <= 10^5
1 <= bloomDay[i] <= 10^9
1 <= m <= 10^6
1 <= k <= n
|
class Solution:
def is_good(self, day):
bouqet_count = 0
cont_count = 0
for d in self.bloomDay:
if d <= day:
cont_count += 1
else:
bouqet_count += cont_count // self.k
cont_count = 0
bouqet_count += cont_count // self.k
return bouqet_count >= self.m
def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
self.bloomDay = bloomDay
self.m = m
self.k = k
if m * k > len(bloomDay):
return -1
start = 1
end = 10**9
while start != end:
middle = (start + end) // 2
if self.is_good(middle):
end = middle
else:
start = middle + 1
return start
|
Given an integer array bloomDay, an integer m and an integer k.
We need to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.
Example 1:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 1
Output: 3
Explanation: Let's see what happened in the first three days. x means flower bloomed and _ means flower didn't bloom in the garden.
We need 3 bouquets each should contain 1 flower.
After day 1: [x, _, _, _, _] // we can only make one bouquet.
After day 2: [x, _, _, _, x] // we can only make two bouquets.
After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.
Example 2:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 2
Output: -1
Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.
Example 3:
Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3
Output: 12
Explanation: We need 2 bouquets each should have 3 flowers.
Here's the garden after the 7 and 12 days:
After day 7: [x, x, x, x, _, x, x]
We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.
After day 12: [x, x, x, x, x, x, x]
It is obvious that we can make two bouquets in different ways.
Example 4:
Input: bloomDay = [1000000000,1000000000], m = 1, k = 1
Output: 1000000000
Explanation: You need to wait 1000000000 days to have a flower ready for a bouquet.
Example 5:
Input: bloomDay = [1,10,2,9,3,8,4,7,5,6], m = 4, k = 2
Output: 9
Constraints:
bloomDay.length == n
1 <= n <= 10^5
1 <= bloomDay[i] <= 10^9
1 <= m <= 10^6
1 <= k <= n
|
class Solution:
def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
b=bloomDay
if m*k>len(b):
return -1
else:
def posb(c)->bool:
p=0
l=0
for i in range(len(b)):
if b[i]>c:
l=0
else:
l+=1
if l==k:
p+=1
l=0
#print(p,c)
return p>=m
l,r=min(b),max(b)
while l<r:
mid=l+(r-l)//2
if posb(mid):
r=mid
else:
l=mid+1
return l
|
Given an integer array bloomDay, an integer m and an integer k.
We need to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.
Example 1:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 1
Output: 3
Explanation: Let's see what happened in the first three days. x means flower bloomed and _ means flower didn't bloom in the garden.
We need 3 bouquets each should contain 1 flower.
After day 1: [x, _, _, _, _] // we can only make one bouquet.
After day 2: [x, _, _, _, x] // we can only make two bouquets.
After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.
Example 2:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 2
Output: -1
Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.
Example 3:
Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3
Output: 12
Explanation: We need 2 bouquets each should have 3 flowers.
Here's the garden after the 7 and 12 days:
After day 7: [x, x, x, x, _, x, x]
We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.
After day 12: [x, x, x, x, x, x, x]
It is obvious that we can make two bouquets in different ways.
Example 4:
Input: bloomDay = [1000000000,1000000000], m = 1, k = 1
Output: 1000000000
Explanation: You need to wait 1000000000 days to have a flower ready for a bouquet.
Example 5:
Input: bloomDay = [1,10,2,9,3,8,4,7,5,6], m = 4, k = 2
Output: 9
Constraints:
bloomDay.length == n
1 <= n <= 10^5
1 <= bloomDay[i] <= 10^9
1 <= m <= 10^6
1 <= k <= n
|
class Solution:
def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
# minDay
# we need k consecutive elems in bloomDay list where all those elems <= minDay
# we need m such groups
# minimum possible val is min val in the list
# maxmimum possible val is max val in the list
# impossible case: m * k > list size
if m * k > len(bloomDay):
return -1
def condition(minDay):
numB = m
curF = 0
for day in bloomDay:
if day <= minDay:
curF += 1
if curF == k:
numB -= 1
curF = 0
if numB == 0:
break
else:
curF = 0
return numB == 0
l = min(bloomDay)
r = max(bloomDay)
# possible = 0
while l < r:
mid = l + (r - l) // 2
if condition(mid):
r = mid
else:
l = mid + 1
return l
|
Given an integer array bloomDay, an integer m and an integer k.
We need to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.
Example 1:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 1
Output: 3
Explanation: Let's see what happened in the first three days. x means flower bloomed and _ means flower didn't bloom in the garden.
We need 3 bouquets each should contain 1 flower.
After day 1: [x, _, _, _, _] // we can only make one bouquet.
After day 2: [x, _, _, _, x] // we can only make two bouquets.
After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.
Example 2:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 2
Output: -1
Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.
Example 3:
Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3
Output: 12
Explanation: We need 2 bouquets each should have 3 flowers.
Here's the garden after the 7 and 12 days:
After day 7: [x, x, x, x, _, x, x]
We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.
After day 12: [x, x, x, x, x, x, x]
It is obvious that we can make two bouquets in different ways.
Example 4:
Input: bloomDay = [1000000000,1000000000], m = 1, k = 1
Output: 1000000000
Explanation: You need to wait 1000000000 days to have a flower ready for a bouquet.
Example 5:
Input: bloomDay = [1,10,2,9,3,8,4,7,5,6], m = 4, k = 2
Output: 9
Constraints:
bloomDay.length == n
1 <= n <= 10^5
1 <= bloomDay[i] <= 10^9
1 <= m <= 10^6
1 <= k <= n
|
class Solution:
def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
if m * k > len(bloomDay): return -1
else:
left, right = 0, max(bloomDay)
while left < right:
mid = (left + right) // 2
flow, bq = 0,0
for d in bloomDay:
if d > mid:
flow = 0
else:
flow += 1
if flow == k:
bq += 1
flow = 0
if bq == m:
break
if bq == m:
right = mid
else:
left = mid + 1
return left
|
Given an integer array bloomDay, an integer m and an integer k.
We need to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.
Example 1:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 1
Output: 3
Explanation: Let's see what happened in the first three days. x means flower bloomed and _ means flower didn't bloom in the garden.
We need 3 bouquets each should contain 1 flower.
After day 1: [x, _, _, _, _] // we can only make one bouquet.
After day 2: [x, _, _, _, x] // we can only make two bouquets.
After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.
Example 2:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 2
Output: -1
Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.
Example 3:
Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3
Output: 12
Explanation: We need 2 bouquets each should have 3 flowers.
Here's the garden after the 7 and 12 days:
After day 7: [x, x, x, x, _, x, x]
We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.
After day 12: [x, x, x, x, x, x, x]
It is obvious that we can make two bouquets in different ways.
Example 4:
Input: bloomDay = [1000000000,1000000000], m = 1, k = 1
Output: 1000000000
Explanation: You need to wait 1000000000 days to have a flower ready for a bouquet.
Example 5:
Input: bloomDay = [1,10,2,9,3,8,4,7,5,6], m = 4, k = 2
Output: 9
Constraints:
bloomDay.length == n
1 <= n <= 10^5
1 <= bloomDay[i] <= 10^9
1 <= m <= 10^6
1 <= k <= n
|
class Solution:
def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
n = len(bloomDay)
if m * k > n:
return -1
vals = list(set(bloomDay))
vals.sort()
def invalid(threshold):
cur = 0
bouquets = 0
for x in bloomDay:
if x <= threshold:
cur += 1
else:
bouquets += cur // k
cur = 0
bouquets += cur // k
return bouquets < m
left, right = 0, len(vals) - 1
while left <= right:
mid = (left + right) // 2
# print(left, right, mid)
if invalid(vals[mid]):
left = mid + 1
else:
right = mid - 1
return vals[left]
|
Given an integer array bloomDay, an integer m and an integer k.
We need to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.
Example 1:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 1
Output: 3
Explanation: Let's see what happened in the first three days. x means flower bloomed and _ means flower didn't bloom in the garden.
We need 3 bouquets each should contain 1 flower.
After day 1: [x, _, _, _, _] // we can only make one bouquet.
After day 2: [x, _, _, _, x] // we can only make two bouquets.
After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.
Example 2:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 2
Output: -1
Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.
Example 3:
Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3
Output: 12
Explanation: We need 2 bouquets each should have 3 flowers.
Here's the garden after the 7 and 12 days:
After day 7: [x, x, x, x, _, x, x]
We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.
After day 12: [x, x, x, x, x, x, x]
It is obvious that we can make two bouquets in different ways.
Example 4:
Input: bloomDay = [1000000000,1000000000], m = 1, k = 1
Output: 1000000000
Explanation: You need to wait 1000000000 days to have a flower ready for a bouquet.
Example 5:
Input: bloomDay = [1,10,2,9,3,8,4,7,5,6], m = 4, k = 2
Output: 9
Constraints:
bloomDay.length == n
1 <= n <= 10^5
1 <= bloomDay[i] <= 10^9
1 <= m <= 10^6
1 <= k <= n
|
class Solution:
def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
def check(bloomDay, day, m, k):
count = 0
for flower in bloomDay:
if flower <= day:
count += 1
if count == k:
m -= 1
count = 0
if m == 0:
return True
else:
count = 0
return False
start = min(bloomDay)
end = max(bloomDay)
res = -1
while start <= end:
center = start + (end - start) // 2
if check(bloomDay, center, m, k):
res = center
end = center - 1
else:
start = center + 1
return res
|
Given an integer array bloomDay, an integer m and an integer k.
We need to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.
Example 1:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 1
Output: 3
Explanation: Let's see what happened in the first three days. x means flower bloomed and _ means flower didn't bloom in the garden.
We need 3 bouquets each should contain 1 flower.
After day 1: [x, _, _, _, _] // we can only make one bouquet.
After day 2: [x, _, _, _, x] // we can only make two bouquets.
After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.
Example 2:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 2
Output: -1
Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.
Example 3:
Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3
Output: 12
Explanation: We need 2 bouquets each should have 3 flowers.
Here's the garden after the 7 and 12 days:
After day 7: [x, x, x, x, _, x, x]
We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.
After day 12: [x, x, x, x, x, x, x]
It is obvious that we can make two bouquets in different ways.
Example 4:
Input: bloomDay = [1000000000,1000000000], m = 1, k = 1
Output: 1000000000
Explanation: You need to wait 1000000000 days to have a flower ready for a bouquet.
Example 5:
Input: bloomDay = [1,10,2,9,3,8,4,7,5,6], m = 4, k = 2
Output: 9
Constraints:
bloomDay.length == n
1 <= n <= 10^5
1 <= bloomDay[i] <= 10^9
1 <= m <= 10^6
1 <= k <= n
|
class Solution:
def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
def isValid(val):
count = 0
tmp = 0
for i in range(len(bloomDay)):
if bloomDay[i] <= val:
tmp += 1
if tmp == k:
count += 1
if count == m:
return True
tmp = 0
else:
tmp = 0
return False
ls = len(bloomDay)
if m * k > ls:
return -1
l, r = min(bloomDay), max(bloomDay)
while l < r:
mid = (l + r) // 2
if isValid(mid):
r = mid
else:
l = mid + 1
return l
|
Given an integer array bloomDay, an integer m and an integer k.
We need to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.
Example 1:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 1
Output: 3
Explanation: Let's see what happened in the first three days. x means flower bloomed and _ means flower didn't bloom in the garden.
We need 3 bouquets each should contain 1 flower.
After day 1: [x, _, _, _, _] // we can only make one bouquet.
After day 2: [x, _, _, _, x] // we can only make two bouquets.
After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.
Example 2:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 2
Output: -1
Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.
Example 3:
Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3
Output: 12
Explanation: We need 2 bouquets each should have 3 flowers.
Here's the garden after the 7 and 12 days:
After day 7: [x, x, x, x, _, x, x]
We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.
After day 12: [x, x, x, x, x, x, x]
It is obvious that we can make two bouquets in different ways.
Example 4:
Input: bloomDay = [1000000000,1000000000], m = 1, k = 1
Output: 1000000000
Explanation: You need to wait 1000000000 days to have a flower ready for a bouquet.
Example 5:
Input: bloomDay = [1,10,2,9,3,8,4,7,5,6], m = 4, k = 2
Output: 9
Constraints:
bloomDay.length == n
1 <= n <= 10^5
1 <= bloomDay[i] <= 10^9
1 <= m <= 10^6
1 <= k <= n
|
class Solution:
def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
# 花的总数>=m*k则一定能完成
n = len(bloomDay)
if n < m * k:
return -1
# 搜索所有可能的天数, 如果第x天无法满足条件, x-1, x-2...也无法满足条件
# 二分查找 满足条件最小k的模板
lo = 1
hi = max(bloomDay)
while lo < hi:
mid = (lo + hi) // 2
if self.can_make(mid, bloomDay, m, k):
hi = mid
else:
lo = mid + 1
return lo
def can_make(self, day, bloomDay, m, k):
cnt = 0
for d in bloomDay:
if d <= day:
cnt += 1
else:
cnt = 0
if cnt == k:
m -= 1
cnt = 0
if m == 0:
return True
return m == 0
|
Given an integer array bloomDay, an integer m and an integer k.
We need to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.
Example 1:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 1
Output: 3
Explanation: Let's see what happened in the first three days. x means flower bloomed and _ means flower didn't bloom in the garden.
We need 3 bouquets each should contain 1 flower.
After day 1: [x, _, _, _, _] // we can only make one bouquet.
After day 2: [x, _, _, _, x] // we can only make two bouquets.
After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.
Example 2:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 2
Output: -1
Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.
Example 3:
Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3
Output: 12
Explanation: We need 2 bouquets each should have 3 flowers.
Here's the garden after the 7 and 12 days:
After day 7: [x, x, x, x, _, x, x]
We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.
After day 12: [x, x, x, x, x, x, x]
It is obvious that we can make two bouquets in different ways.
Example 4:
Input: bloomDay = [1000000000,1000000000], m = 1, k = 1
Output: 1000000000
Explanation: You need to wait 1000000000 days to have a flower ready for a bouquet.
Example 5:
Input: bloomDay = [1,10,2,9,3,8,4,7,5,6], m = 4, k = 2
Output: 9
Constraints:
bloomDay.length == n
1 <= n <= 10^5
1 <= bloomDay[i] <= 10^9
1 <= m <= 10^6
1 <= k <= n
|
class Solution:
def checkDay(self,day,bloomDay,m,k)->bool:
y,count=0,0
for i in range(len(bloomDay)):
if bloomDay[i] <= day:
#bloomed.append(1)
y+=1
else:
#bloomed.append(0)
y=0
if y==k:
count+=1
y=0
if count==m:
return True
return False
def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
'''
bloomDay: Flower garden, elements are # of days required for that flower to bloom
m: # of bouquets needed
k: # of adjacent flowers needed in each bouquet
First, check to see if mk>len(bloomDay). If so return -1
Then, see how many days needed until mk flowers have bloomed
Check to see if they are adjacent
if so return days
else maybe check how many adjacents are needed, or go to the next day
'''
#bloomDay,m,k = [7,7,7,7,12,7,7],2,3
FN=m*k # (Flowers Needed)
if FN > len(bloomDay):
return -1
# After x days, is it possible to create m bouquets?
bloomed=sorted(bloomDay)
lastWorking,count,start,stop=-1,0,0,len(bloomed)
#print(bloomed)
half=stop//2
#day=bloomed[half]
while(start<=half<stop):
day=bloomed[half]
#print('Half: ',half,', Day: ',day,' || Bounds: ',start,', ',stop)
# If current day works, check previous day
if self.checkDay(day,bloomDay,m,k):
#print('Day: ',day,' works')
lastWorking,stop=day,half
# Otherwise check half of new bounds
else:
start=half+1
half=(start+stop)//2
return lastWorking
|
Given an integer array bloomDay, an integer m and an integer k.
We need to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.
Example 1:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 1
Output: 3
Explanation: Let's see what happened in the first three days. x means flower bloomed and _ means flower didn't bloom in the garden.
We need 3 bouquets each should contain 1 flower.
After day 1: [x, _, _, _, _] // we can only make one bouquet.
After day 2: [x, _, _, _, x] // we can only make two bouquets.
After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.
Example 2:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 2
Output: -1
Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.
Example 3:
Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3
Output: 12
Explanation: We need 2 bouquets each should have 3 flowers.
Here's the garden after the 7 and 12 days:
After day 7: [x, x, x, x, _, x, x]
We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.
After day 12: [x, x, x, x, x, x, x]
It is obvious that we can make two bouquets in different ways.
Example 4:
Input: bloomDay = [1000000000,1000000000], m = 1, k = 1
Output: 1000000000
Explanation: You need to wait 1000000000 days to have a flower ready for a bouquet.
Example 5:
Input: bloomDay = [1,10,2,9,3,8,4,7,5,6], m = 4, k = 2
Output: 9
Constraints:
bloomDay.length == n
1 <= n <= 10^5
1 <= bloomDay[i] <= 10^9
1 <= m <= 10^6
1 <= k <= n
|
class Solution:
def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
if m * k > len(bloomDay):
return -1
def feasible(days,m,k):
flowers =0
bouq =0
for item in bloomDay:
if item <= days:
flowers +=1
else:
flowers =0
if flowers >=k:
bouq +=1
flowers =0
if bouq == m:
return True
return False
left = min(bloomDay) # min number of days
right = max(bloomDay)# maximum number of days
while left < right:
mid = left + (right-left) //2
if feasible(mid,m,k):
right = mid
else:
left = mid +1
return left
|
Given an integer array bloomDay, an integer m and an integer k.
We need to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.
Example 1:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 1
Output: 3
Explanation: Let's see what happened in the first three days. x means flower bloomed and _ means flower didn't bloom in the garden.
We need 3 bouquets each should contain 1 flower.
After day 1: [x, _, _, _, _] // we can only make one bouquet.
After day 2: [x, _, _, _, x] // we can only make two bouquets.
After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.
Example 2:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 2
Output: -1
Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.
Example 3:
Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3
Output: 12
Explanation: We need 2 bouquets each should have 3 flowers.
Here's the garden after the 7 and 12 days:
After day 7: [x, x, x, x, _, x, x]
We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.
After day 12: [x, x, x, x, x, x, x]
It is obvious that we can make two bouquets in different ways.
Example 4:
Input: bloomDay = [1000000000,1000000000], m = 1, k = 1
Output: 1000000000
Explanation: You need to wait 1000000000 days to have a flower ready for a bouquet.
Example 5:
Input: bloomDay = [1,10,2,9,3,8,4,7,5,6], m = 4, k = 2
Output: 9
Constraints:
bloomDay.length == n
1 <= n <= 10^5
1 <= bloomDay[i] <= 10^9
1 <= m <= 10^6
1 <= k <= n
|
class Solution:
def minDays(self, bloomDay: List[int], M: int, K: int) -> int:
if len(bloomDay) < M * K : return -1
def condition(day) -> bool:
m, k = 0, 0
for bd in bloomDay:
if bd <= day : k += 1
else : k = 0
if k >= K :
m += 1
k = 0
if m >= M : return True
return False
left, right = min(bloomDay), max(bloomDay)
while left < right:
mid = left + (right - left) // 2
if condition(mid):
right = mid
else:
left = mid + 1
return left
|
Given an integer array bloomDay, an integer m and an integer k.
We need to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.
Example 1:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 1
Output: 3
Explanation: Let's see what happened in the first three days. x means flower bloomed and _ means flower didn't bloom in the garden.
We need 3 bouquets each should contain 1 flower.
After day 1: [x, _, _, _, _] // we can only make one bouquet.
After day 2: [x, _, _, _, x] // we can only make two bouquets.
After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.
Example 2:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 2
Output: -1
Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.
Example 3:
Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3
Output: 12
Explanation: We need 2 bouquets each should have 3 flowers.
Here's the garden after the 7 and 12 days:
After day 7: [x, x, x, x, _, x, x]
We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.
After day 12: [x, x, x, x, x, x, x]
It is obvious that we can make two bouquets in different ways.
Example 4:
Input: bloomDay = [1000000000,1000000000], m = 1, k = 1
Output: 1000000000
Explanation: You need to wait 1000000000 days to have a flower ready for a bouquet.
Example 5:
Input: bloomDay = [1,10,2,9,3,8,4,7,5,6], m = 4, k = 2
Output: 9
Constraints:
bloomDay.length == n
1 <= n <= 10^5
1 <= bloomDay[i] <= 10^9
1 <= m <= 10^6
1 <= k <= n
|
class Solution:
def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
n = len(bloomDay)
if n//k < m:
return -1
left = min(bloomDay)
right = max(bloomDay)
while left < right:
mid = (left + right)//2
numBouqets = 0
count = 0
for i in range(n):
if bloomDay[i]<=mid:
count += 1
else:
count = 0
if count == k:
count = 0
numBouqets += 1
# print(left, mid, right, numBouqets)
if numBouqets >= m:
right = mid
else:
left = mid+1
return left
|
Given a binary string s (a string consisting only of '0' and '1's).
Return the number of substrings with all characters 1's.
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: s = "0110111"
Output: 9
Explanation: There are 9 substring in total with only 1's characters.
"1" -> 5 times.
"11" -> 3 times.
"111" -> 1 time.
Example 2:
Input: s = "101"
Output: 2
Explanation: Substring "1" is shown 2 times in s.
Example 3:
Input: s = "111111"
Output: 21
Explanation: Each substring contains only 1's characters.
Example 4:
Input: s = "000"
Output: 0
Constraints:
s[i] == '0' or s[i] == '1'
1 <= s.length <= 10^5
|
class Solution:
def numSub(self, s: str) -> int:
# 10/6/20
dic = collections.defaultdict(int)
n = len(s)
left, right = 0, 0
while left < n:
if s[left] == '1':
right = left
while right < n and s[right] == '1':
right += 1
dic[right-left] += 1
left = right
else:
left += 1
total = 0
for ones in dic:
total = (total + (ones *(ones+1)) // 2 * dic[ones]) % (10**9 + 7)
return total
|
Given a binary string s (a string consisting only of '0' and '1's).
Return the number of substrings with all characters 1's.
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: s = "0110111"
Output: 9
Explanation: There are 9 substring in total with only 1's characters.
"1" -> 5 times.
"11" -> 3 times.
"111" -> 1 time.
Example 2:
Input: s = "101"
Output: 2
Explanation: Substring "1" is shown 2 times in s.
Example 3:
Input: s = "111111"
Output: 21
Explanation: Each substring contains only 1's characters.
Example 4:
Input: s = "000"
Output: 0
Constraints:
s[i] == '0' or s[i] == '1'
1 <= s.length <= 10^5
|
class Solution:
def calc_num_variations(self, num_ones, memo):
if num_ones in memo:
return memo[num_ones]
curr_sum = 0
for x in range(num_ones+1):
curr_sum += x
if not x in memo:
memo[x] = curr_sum
memo[num_ones] = curr_sum
return curr_sum
def numSub(self, s: str) -> int:
memo = {}
num_ones = 0
num_variations = 0
for one in s:
if one == '1':
num_ones += 1
else:
num_variations += self.calc_num_variations(num_ones, memo)
num_ones = 0
if num_ones > 0:
num_variations += self.calc_num_variations(num_ones, memo)
return num_variations%(10**9 + 7)
|
Given a binary string s (a string consisting only of '0' and '1's).
Return the number of substrings with all characters 1's.
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: s = "0110111"
Output: 9
Explanation: There are 9 substring in total with only 1's characters.
"1" -> 5 times.
"11" -> 3 times.
"111" -> 1 time.
Example 2:
Input: s = "101"
Output: 2
Explanation: Substring "1" is shown 2 times in s.
Example 3:
Input: s = "111111"
Output: 21
Explanation: Each substring contains only 1's characters.
Example 4:
Input: s = "000"
Output: 0
Constraints:
s[i] == '0' or s[i] == '1'
1 <= s.length <= 10^5
|
class Solution:
def numSub(self, s: str) -> int:
res = 0
i = 0
mod = (int)(1e9+7)
while i < len(s):
if s[i]!='1':
i+=1
continue
start = i
while i<len(s) and s[i] == '1':
i+=1
count = i-start
res += count*(count+1)/2
res %= mod
return int(res)
|
Given a binary string s (a string consisting only of '0' and '1's).
Return the number of substrings with all characters 1's.
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: s = "0110111"
Output: 9
Explanation: There are 9 substring in total with only 1's characters.
"1" -> 5 times.
"11" -> 3 times.
"111" -> 1 time.
Example 2:
Input: s = "101"
Output: 2
Explanation: Substring "1" is shown 2 times in s.
Example 3:
Input: s = "111111"
Output: 21
Explanation: Each substring contains only 1's characters.
Example 4:
Input: s = "000"
Output: 0
Constraints:
s[i] == '0' or s[i] == '1'
1 <= s.length <= 10^5
|
class Solution:
def numSub(self, s: str) -> int:
res = 0
mod = pow(10,9) + 7
i = 0
while i< len(s):
cnt = 0
while i < len(s) and s[i] == '1':
cnt+=1
i+=1
i+=1
res += (cnt*(cnt+1))//2 % mod
return res
|
Given a binary string s (a string consisting only of '0' and '1's).
Return the number of substrings with all characters 1's.
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: s = "0110111"
Output: 9
Explanation: There are 9 substring in total with only 1's characters.
"1" -> 5 times.
"11" -> 3 times.
"111" -> 1 time.
Example 2:
Input: s = "101"
Output: 2
Explanation: Substring "1" is shown 2 times in s.
Example 3:
Input: s = "111111"
Output: 21
Explanation: Each substring contains only 1's characters.
Example 4:
Input: s = "000"
Output: 0
Constraints:
s[i] == '0' or s[i] == '1'
1 <= s.length <= 10^5
|
class Solution:
def numSub(self, s: str) -> int:
n = len(s)
start = 0
while start < n and s[start] != '1':
start += 1
if start == n:
return 0
i = start
count = 0
while i < n and start < n:
if s[i] == '1':
count += i - start + 1
count = count % (10**9 + 7)
i += 1
continue
start = i
while start < n and s[start] != '1':
start += 1
i = start
return count
|
Given a binary string s (a string consisting only of '0' and '1's).
Return the number of substrings with all characters 1's.
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: s = "0110111"
Output: 9
Explanation: There are 9 substring in total with only 1's characters.
"1" -> 5 times.
"11" -> 3 times.
"111" -> 1 time.
Example 2:
Input: s = "101"
Output: 2
Explanation: Substring "1" is shown 2 times in s.
Example 3:
Input: s = "111111"
Output: 21
Explanation: Each substring contains only 1's characters.
Example 4:
Input: s = "000"
Output: 0
Constraints:
s[i] == '0' or s[i] == '1'
1 <= s.length <= 10^5
|
class Solution:
def numSub(self, s: str) -> int:
result, stop_idx = 0, -1
for idx, char in enumerate(s):
if char != '1' or idx <= stop_idx:
continue
freq = 1
next_idx = idx + 1
while (next_idx < len(s) and s[next_idx] == '1'):
freq += 1
stop_idx = next_idx
next_idx += 1
result += (freq + 1)*freq/2
return int(result % (1e9 + 7))
|
Given a binary string s (a string consisting only of '0' and '1's).
Return the number of substrings with all characters 1's.
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: s = "0110111"
Output: 9
Explanation: There are 9 substring in total with only 1's characters.
"1" -> 5 times.
"11" -> 3 times.
"111" -> 1 time.
Example 2:
Input: s = "101"
Output: 2
Explanation: Substring "1" is shown 2 times in s.
Example 3:
Input: s = "111111"
Output: 21
Explanation: Each substring contains only 1's characters.
Example 4:
Input: s = "000"
Output: 0
Constraints:
s[i] == '0' or s[i] == '1'
1 <= s.length <= 10^5
|
class Solution:
def numSub(self, s: str) -> int:
cont_one_count = 0
one_sub = 0
for char in s:
if char=='1':
cont_one_count+=1
if char=='0':
one_sub+=(cont_one_count*(cont_one_count+1))/2
cont_one_count=0
one_sub+=(cont_one_count*(cont_one_count+1))/2
return int(one_sub)%(10**9+7)
|
Given a binary string s (a string consisting only of '0' and '1's).
Return the number of substrings with all characters 1's.
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: s = "0110111"
Output: 9
Explanation: There are 9 substring in total with only 1's characters.
"1" -> 5 times.
"11" -> 3 times.
"111" -> 1 time.
Example 2:
Input: s = "101"
Output: 2
Explanation: Substring "1" is shown 2 times in s.
Example 3:
Input: s = "111111"
Output: 21
Explanation: Each substring contains only 1's characters.
Example 4:
Input: s = "000"
Output: 0
Constraints:
s[i] == '0' or s[i] == '1'
1 <= s.length <= 10^5
|
class Solution:
def numSub(self, s: str) -> int:
result, stop_idx = 0, -1
for idx, char in enumerate(s):
if char != '1':
continue
if idx <= stop_idx:
continue
freq = 1
next_idx = idx + 1
while (next_idx < len(s) and s[next_idx] == '1'):
freq += 1
stop_idx = next_idx
next_idx += 1
result += (freq + 1)*freq/2
return int(result % (1e9 + 7))
|
Given a binary string s (a string consisting only of '0' and '1's).
Return the number of substrings with all characters 1's.
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: s = "0110111"
Output: 9
Explanation: There are 9 substring in total with only 1's characters.
"1" -> 5 times.
"11" -> 3 times.
"111" -> 1 time.
Example 2:
Input: s = "101"
Output: 2
Explanation: Substring "1" is shown 2 times in s.
Example 3:
Input: s = "111111"
Output: 21
Explanation: Each substring contains only 1's characters.
Example 4:
Input: s = "000"
Output: 0
Constraints:
s[i] == '0' or s[i] == '1'
1 <= s.length <= 10^5
|
class Solution:
def numSub(self, s: str) -> int:
self.s = s
modulo = 1000000007
def numSub(s):
sOne = ''
sSub = []
for i in range(len(s)):
if s[i] == '1':
sOne += '1'
if i != len(s) - 1:
if s[i + 1] == '1':
continue
else:
sSub.append(sOne)
sOne = ''
else:
sSub.append(sOne)
return sSub
sSub = numSub(s)
num_sOne = 0
for sOne in sSub:
len_sOne = len(sOne)
num_sOne += ((len_sOne * (len_sOne + 1)) // 2) % modulo
num_sOne %= modulo
return int(num_sOne)
|
Given a binary string s (a string consisting only of '0' and '1's).
Return the number of substrings with all characters 1's.
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: s = "0110111"
Output: 9
Explanation: There are 9 substring in total with only 1's characters.
"1" -> 5 times.
"11" -> 3 times.
"111" -> 1 time.
Example 2:
Input: s = "101"
Output: 2
Explanation: Substring "1" is shown 2 times in s.
Example 3:
Input: s = "111111"
Output: 21
Explanation: Each substring contains only 1's characters.
Example 4:
Input: s = "000"
Output: 0
Constraints:
s[i] == '0' or s[i] == '1'
1 <= s.length <= 10^5
|
class Solution:
def numSub(self, s: str) -> int:
num_lst = []
ans = 0
temp = 0
for n in s:
if n == '1':
temp += 1
if n == '0' and temp != 0:
num_lst.append(temp)
temp = 0
if temp != 0: num_lst.append(temp)
if len(num_lst) == 0: return 0
for num in num_lst:
while num != 0:
ans += num
num -= 1
return ans % ((10**9) + 7)
|
Given a binary string s (a string consisting only of '0' and '1's).
Return the number of substrings with all characters 1's.
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: s = "0110111"
Output: 9
Explanation: There are 9 substring in total with only 1's characters.
"1" -> 5 times.
"11" -> 3 times.
"111" -> 1 time.
Example 2:
Input: s = "101"
Output: 2
Explanation: Substring "1" is shown 2 times in s.
Example 3:
Input: s = "111111"
Output: 21
Explanation: Each substring contains only 1's characters.
Example 4:
Input: s = "000"
Output: 0
Constraints:
s[i] == '0' or s[i] == '1'
1 <= s.length <= 10^5
|
class Solution:
def numSub(self, s: str) -> int:
n = len(s)
i = 0
count = 0
while (i<n):
if s[i] == '1':
seq = 0
while (i<n) and (s[i] == '1'):
seq += 1
i += 1
count += seq*(seq+1)//2
else:
i += 1
print(count%(10**9 + 7))
return count%(10**9 + 7)
|
Given a binary string s (a string consisting only of '0' and '1's).
Return the number of substrings with all characters 1's.
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: s = "0110111"
Output: 9
Explanation: There are 9 substring in total with only 1's characters.
"1" -> 5 times.
"11" -> 3 times.
"111" -> 1 time.
Example 2:
Input: s = "101"
Output: 2
Explanation: Substring "1" is shown 2 times in s.
Example 3:
Input: s = "111111"
Output: 21
Explanation: Each substring contains only 1's characters.
Example 4:
Input: s = "000"
Output: 0
Constraints:
s[i] == '0' or s[i] == '1'
1 <= s.length <= 10^5
|
class Solution:
def numSub(self, s: str) -> int:
sum = cnt = 0
for c in s:
if c == '1':
cnt += 1
sum = (sum + cnt) % (10 ** 9 + 7)
else:
cnt = 0
return sum
|
You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j].
Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so.
Example 1:
Input: s1 = "xx", s2 = "yy"
Output: 1
Explanation:
Swap s1[0] and s2[1], s1 = "yx", s2 = "yx".
Example 2:
Input: s1 = "xy", s2 = "yx"
Output: 2
Explanation:
Swap s1[0] and s2[0], s1 = "yy", s2 = "xx".
Swap s1[0] and s2[1], s1 = "xy", s2 = "xy".
Note that you can't swap s1[0] and s1[1] to make s1 equal to "yx", cause we can only swap chars in different strings.
Example 3:
Input: s1 = "xx", s2 = "xy"
Output: -1
Example 4:
Input: s1 = "xxyyxyxyxx", s2 = "xyyxyxxxyx"
Output: 4
Constraints:
1 <= s1.length, s2.length <= 1000
s1, s2 only contain 'x' or 'y'.
|
class Solution:
def minimumSwap(self, s1: str, s2: str) -> int:
xy_pair = 0
yx_pair = 0
for c1, c2 in zip(s1, s2):
if c1 == 'x' and c2 == 'y':
xy_pair += 1
elif c1 == 'y' and c2 == 'x':
yx_pair += 1
if (xy_pair + yx_pair)%2 == 1:
return -1
return xy_pair//2 + yx_pair//2 + xy_pair%2 + yx_pair%2
'''
\"xx\"
\"yy\"
\"xy\"
\"yx\"
\"xx\"
\"xy\"
\"xyxy\"
\"yxyx\"
\"xxyyxxyxyxyx\"
\"xyxyxyxxyyxx\"
\"xxyyxyxyxx\"
\"xyyxyxxxyx\"
\"xyxyxyyxx\"
\"yxyyyxxxx\"
\"xyxyxyyxxxyyxyxxxyx\"
\"yxyyyxxxxxxyyxyxyxx\"
'''
|
You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j].
Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so.
Example 1:
Input: s1 = "xx", s2 = "yy"
Output: 1
Explanation:
Swap s1[0] and s2[1], s1 = "yx", s2 = "yx".
Example 2:
Input: s1 = "xy", s2 = "yx"
Output: 2
Explanation:
Swap s1[0] and s2[0], s1 = "yy", s2 = "xx".
Swap s1[0] and s2[1], s1 = "xy", s2 = "xy".
Note that you can't swap s1[0] and s1[1] to make s1 equal to "yx", cause we can only swap chars in different strings.
Example 3:
Input: s1 = "xx", s2 = "xy"
Output: -1
Example 4:
Input: s1 = "xxyyxyxyxx", s2 = "xyyxyxxxyx"
Output: 4
Constraints:
1 <= s1.length, s2.length <= 1000
s1, s2 only contain 'x' or 'y'.
|
class Solution:
def minimumSwap(self, s1: str, s2: str) -> int:
h = defaultdict(int)
count = 0
for i in range(len(s1)):
if s1[i] != s2[i]:
count += 1
h[s1[i]] += 1
if count % 2 != 0:
return -1
res, a, b = 0, h['x'], h['y']
res += a // 2 + b // 2
if a % 2 == 0:
return res
return res + 2
|
You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j].
Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so.
Example 1:
Input: s1 = "xx", s2 = "yy"
Output: 1
Explanation:
Swap s1[0] and s2[1], s1 = "yx", s2 = "yx".
Example 2:
Input: s1 = "xy", s2 = "yx"
Output: 2
Explanation:
Swap s1[0] and s2[0], s1 = "yy", s2 = "xx".
Swap s1[0] and s2[1], s1 = "xy", s2 = "xy".
Note that you can't swap s1[0] and s1[1] to make s1 equal to "yx", cause we can only swap chars in different strings.
Example 3:
Input: s1 = "xx", s2 = "xy"
Output: -1
Example 4:
Input: s1 = "xxyyxyxyxx", s2 = "xyyxyxxxyx"
Output: 4
Constraints:
1 <= s1.length, s2.length <= 1000
s1, s2 only contain 'x' or 'y'.
|
class Solution:
def minimumSwap(self, s1: str, s2: str) -> int:
x_y,y_x = 0,0
for i,j in zip(s1,s2):
if i != j:
if i == 'x':
x_y += 1
else:
y_x += 1
if (x_y + y_x)%2 == 1:
return -1
res = 0
res += x_y//2
res += y_x//2
if x_y%2==1:
res += 2
return res
|
You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j].
Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so.
Example 1:
Input: s1 = "xx", s2 = "yy"
Output: 1
Explanation:
Swap s1[0] and s2[1], s1 = "yx", s2 = "yx".
Example 2:
Input: s1 = "xy", s2 = "yx"
Output: 2
Explanation:
Swap s1[0] and s2[0], s1 = "yy", s2 = "xx".
Swap s1[0] and s2[1], s1 = "xy", s2 = "xy".
Note that you can't swap s1[0] and s1[1] to make s1 equal to "yx", cause we can only swap chars in different strings.
Example 3:
Input: s1 = "xx", s2 = "xy"
Output: -1
Example 4:
Input: s1 = "xxyyxyxyxx", s2 = "xyyxyxxxyx"
Output: 4
Constraints:
1 <= s1.length, s2.length <= 1000
s1, s2 only contain 'x' or 'y'.
|
class Solution:
def minimumSwap(self, s1: str, s2: str) -> int:
cntxy, cntyx, n = 0, 0, len(s1)
for i in range(n):
if s1[i] == 'x' and s2[i] == 'y': cntxy += 1
elif s1[i] == 'y' and s2[i] == 'x': cntyx += 1
if (cntxy + cntyx) % 2 == 1: return -1
if cntxy % 2 == 1:
return cntxy // 2 + cntyx // 2 + 2
else: return cntxy // 2 + cntyx // 2
|
You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j].
Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so.
Example 1:
Input: s1 = "xx", s2 = "yy"
Output: 1
Explanation:
Swap s1[0] and s2[1], s1 = "yx", s2 = "yx".
Example 2:
Input: s1 = "xy", s2 = "yx"
Output: 2
Explanation:
Swap s1[0] and s2[0], s1 = "yy", s2 = "xx".
Swap s1[0] and s2[1], s1 = "xy", s2 = "xy".
Note that you can't swap s1[0] and s1[1] to make s1 equal to "yx", cause we can only swap chars in different strings.
Example 3:
Input: s1 = "xx", s2 = "xy"
Output: -1
Example 4:
Input: s1 = "xxyyxyxyxx", s2 = "xyyxyxxxyx"
Output: 4
Constraints:
1 <= s1.length, s2.length <= 1000
s1, s2 only contain 'x' or 'y'.
|
class Solution:
def minimumSwap(self, s1: str, s2: str) -> int:
xx = []
for i in range(len(s1)):
if s1[i] != s2[i]:
xx.append(s1[i])
if len(xx)%2 == 1:
return -1
res = len(xx)//2
if xx.count('x')%2 == 1:
res += 1
return res
|
You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j].
Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so.
Example 1:
Input: s1 = "xx", s2 = "yy"
Output: 1
Explanation:
Swap s1[0] and s2[1], s1 = "yx", s2 = "yx".
Example 2:
Input: s1 = "xy", s2 = "yx"
Output: 2
Explanation:
Swap s1[0] and s2[0], s1 = "yy", s2 = "xx".
Swap s1[0] and s2[1], s1 = "xy", s2 = "xy".
Note that you can't swap s1[0] and s1[1] to make s1 equal to "yx", cause we can only swap chars in different strings.
Example 3:
Input: s1 = "xx", s2 = "xy"
Output: -1
Example 4:
Input: s1 = "xxyyxyxyxx", s2 = "xyyxyxxxyx"
Output: 4
Constraints:
1 <= s1.length, s2.length <= 1000
s1, s2 only contain 'x' or 'y'.
|
class Solution:
def minimumSwap(self, s1: str, s2: str) -> int:
x = 0
y = 0
for index in range(0, len(s1)):
if s1[index] != s2[index]:
if s1[index] == 'x':
x += 1
else:
y += 1
mid = ( x + y ) / 2
x, y = x % 2, y % 2
if x + y == 1:
return -1
if x + y == 2:
mid += 1
print(mid)
return int(mid)
|
You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j].
Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so.
Example 1:
Input: s1 = "xx", s2 = "yy"
Output: 1
Explanation:
Swap s1[0] and s2[1], s1 = "yx", s2 = "yx".
Example 2:
Input: s1 = "xy", s2 = "yx"
Output: 2
Explanation:
Swap s1[0] and s2[0], s1 = "yy", s2 = "xx".
Swap s1[0] and s2[1], s1 = "xy", s2 = "xy".
Note that you can't swap s1[0] and s1[1] to make s1 equal to "yx", cause we can only swap chars in different strings.
Example 3:
Input: s1 = "xx", s2 = "xy"
Output: -1
Example 4:
Input: s1 = "xxyyxyxyxx", s2 = "xyyxyxxxyx"
Output: 4
Constraints:
1 <= s1.length, s2.length <= 1000
s1, s2 only contain 'x' or 'y'.
|
class Solution:
def minimumSwap(self, s1: str, s2: str) -> int:
x_y = y_x = 0
res = 0
for i in range(len(s1)):
if s1[i] != s2[i]:
if s1[i] == 'x':
x_y += 1
else:
y_x += 1
if (x_y + y_x) % 2 == 1:
return -1
res = x_y//2
res += y_x//2
if x_y % 2 == 1:
res += 2
return res
|
You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j].
Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so.
Example 1:
Input: s1 = "xx", s2 = "yy"
Output: 1
Explanation:
Swap s1[0] and s2[1], s1 = "yx", s2 = "yx".
Example 2:
Input: s1 = "xy", s2 = "yx"
Output: 2
Explanation:
Swap s1[0] and s2[0], s1 = "yy", s2 = "xx".
Swap s1[0] and s2[1], s1 = "xy", s2 = "xy".
Note that you can't swap s1[0] and s1[1] to make s1 equal to "yx", cause we can only swap chars in different strings.
Example 3:
Input: s1 = "xx", s2 = "xy"
Output: -1
Example 4:
Input: s1 = "xxyyxyxyxx", s2 = "xyyxyxxxyx"
Output: 4
Constraints:
1 <= s1.length, s2.length <= 1000
s1, s2 only contain 'x' or 'y'.
|
class Solution:
def minimumSwap(self, s1: str, s2: str) -> int:
xy = 0
yx = 0
for m, n in zip(s1, s2): # Each character of s1 is followed by a character of s2 in the associated position.
if m == 'x' and n == 'y':
xy += 1
elif m == 'y' and n == 'x':
yx += 1
if (xy + yx) % 2 != 0:
return -1
else:
return xy // 2 + yx // 2 + xy % 2 + yx % 2
|
You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j].
Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so.
Example 1:
Input: s1 = "xx", s2 = "yy"
Output: 1
Explanation:
Swap s1[0] and s2[1], s1 = "yx", s2 = "yx".
Example 2:
Input: s1 = "xy", s2 = "yx"
Output: 2
Explanation:
Swap s1[0] and s2[0], s1 = "yy", s2 = "xx".
Swap s1[0] and s2[1], s1 = "xy", s2 = "xy".
Note that you can't swap s1[0] and s1[1] to make s1 equal to "yx", cause we can only swap chars in different strings.
Example 3:
Input: s1 = "xx", s2 = "xy"
Output: -1
Example 4:
Input: s1 = "xxyyxyxyxx", s2 = "xyyxyxxxyx"
Output: 4
Constraints:
1 <= s1.length, s2.length <= 1000
s1, s2 only contain 'x' or 'y'.
|
class Solution:
def minimumSwap(self, s1: str, s2: str) -> int:
a = 0
b = 0
for i in range(len(s1)):
if s1[i] == 'x' and s2[i] == 'y' :
a += 1
elif s1[i] == 'y' and s2[i] == 'x':
b += 1
if a % 2 == 0 and b % 2 == 0:
return a // 2 + b // 2
elif a % 2 == 1 and b % 2 == 1:
return a // 2 + b // 2 + 2
else:
return -1
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, strn: str) -> str:
max_prefs = [0]*len(strn)
curr = 0
for idx in range(1, len(strn)):
while True:
if curr == 0:
if strn[idx] == strn[0]:
curr = 1
max_prefs[idx] = curr
break
else:
if strn[idx] == strn[curr]:
curr += 1
max_prefs[idx] = curr
break
else:
curr = max_prefs[curr-1]
return strn[:max_prefs[-1]]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
n = len(s)
lps = [0] * n
j = 0
for i in range(1, n):
if s[i] == s[j]:
j += 1
lps[i] = j
else:
while j > 0:
j = lps[j-1]
if s[j] == s[i]:
j += 1
break
lps[i] = j
return s[:lps[-1]]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
from collections import defaultdict
class TrieNode:
def __init__(self, x=None):
self.val = x
self.end = False
self.children = defaultdict(TrieNode)
class Trie:
def __init__(self):
self.root = TrieNode()
self.max_len = 0
def insert(self, word):
node = self.root
for i, w in enumerate(word):
node.children[w].val = w
node = node.children[w]
self.root.children[w] = node
if i == len(w) - 1:
node.end = True
def find(self, word):
node = self.root
d = 0
for w in word[:-1]:
print(w, node.children.keys())
node = node.children[w]
d += 1
if node.end:
print(node.val, node.end)
self.max_len = max(self.max_len, d)
class Solution:
def longestPrefix(self, s):
res, l, r, mod = 0, 0, 0, 10**9 + 7
for i in range(len(s) - 1):
l = (l * 128 + ord(s[i])) % mod
r = (r + pow(128, i, mod) * ord(s[~i])) % mod
if l == r: res = i + 1
return s[:res]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s):
# res stores the index of the end of the prefix, used for output the result
# l stores the hash key for prefix
# r stores the hash key for suffix
# mod is used to make sure that the hash value doesn't get too big, you can choose another mod value if you want.
res, l, r, mod = 0, 0, 0, 10**9 + 7
# now we start from the beginning and the end of the string
# note you shouldn't search the whole string! because the longest prefix and suffix is the string itself
for i in range(len(s) - 1):
# based on an idea that is similar to prefix sum, we calculate the prefix hash in O(1) time.
# specifically, we multiply the current prefix by 128 (which is the length of ASCII, but you can use another value as well)
# then add in the ASCII value of the upcoming letter
l = (l * 128 + ord(s[i])) % mod
# similarly, we can calculate the suffix hash in O(1) time.
# Specifically, we get the ith letter from the end using s[~i], note ~i is -i-1
# we find the pow(128, i, mod) and multiply by the letter's ASCII value
# Actually, if we don't care about the beautifulness of the code, you can have a variable to keep track of pow(128, i, mod) as you increase i
r = (r + pow(128, i, mod) * ord(s[~i])) % mod
# we check if the prefix and suffix agrees, if yes, we find yet another longer prefix, so we record the index
if l == r: res = i + 1
# after we finish searching the string, output the prefix
return s[:res]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s):
# res stores the index of the end of the prefix, used for output the result
# l stores the hash key for prefix
# r stores the hash key for suffix
# mod is used to make sure that the hash value doesn't get too big, you can choose another mod value if you want.
num_chars = 26
res, l, r, mod = 0, 0, 0, 10**9 + 7
# now we start from the beginning and the end of the string
# note you shouldn't search the whole string! because the longest prefix and suffix is the string itself
for i in range(len(s) - 1):
# based on an idea that is similar to prefix sum, we calculate the prefix hash in O(1) time.
# specifically, we multiply the current prefix by num_chars (which is the length of ASCII, but you can use another value as well)
# then add in the ASCII value of the upcoming letter
l = (l * num_chars + ord(s[i])) % mod
# similarly, we can calculate the suffix hash in O(1) time.
# Specifically, we get the ith letter from the end using s[~i], note ~i is -i-1
# we find the pow(num_chars, i, mod) and multiply by the letter's ASCII value
# Actually, if we don't care about the beautifulness of the code, you can have a variable to keep track of pow(num_chars, i, mod) as you increase i
r = (r + pow(num_chars, i, mod) * ord(s[~i])) % mod
# we check if the prefix and suffix agrees, if yes, we find yet another longer prefix, so we record the index
if l == r: res = i + 1
# after we finish searching the string, output the prefix
return s[:res]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
'''
res keeps track of the index of the end of the prefix, used to output the happy prefix
l stores the hash key for prefix
r tracks the hash key for suffix
'''
res, l, r = 0, 0, 0
mod = 10**9 + 5 # used to ensure that the hash value doesn't overflow
'''
now start from the beginning and end of the string
- note you shouldn't search teh whole string because the longest prefix/suffix is the string itself
'''
for i in range(len(s)-1):
# hash the prefix/suffix in o(1); 128 can be substituted with any value; it just happens to be the length of ASCII
'''
for a given string 'elkmmmelk', prefix elk will be hashed in ascending order.
e: 'e': hash[e] = ord(e)
l: 'el': hash[el] = hash(e)*128 + ord(l)
k: 'elk': hash[elk] = hash(el)*128 + ord(k)
which translates to (l * 128 + ord(s[i]))
suffix elk will be hashed in descending order
k: 'k': hash[k] = ord(k)
l: 'lk': hash[lk] = ord(k) + ord(l) * 128
e: 'elk': hash[elk] = ord(k) + ord(l) * 128 + ord(e) * 128^2
which translates to r + pow(128, i, mod)
'''
l = (l * 128 + ord(s[i])) % mod
r = (r + pow(128, i, mod) * ord(s[-i-1])) % mod
if l == r: # if both hash values match, update res
res = i + 1
return s[:res]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s):
res, l, r, mod = 0, 0, 0, 10**9 + 7
for i in range(len(s) - 1):
l = (l * 128 + ord(s[i])) % mod
r = (r + pow(128, i, mod) * ord(s[~i])) % mod
if l == r:
res = i + 1
return s[:res]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
best = ''
left = 0
right = len(s) - 1
left_s = ''
right_s = ''
hash_left = 0
hash_right = 0
while left < len(s) - 1 and right > 0:
hash_left += ord(s[left])
hash_right += ord(s[right])
left_s += s[left]
right_s = s[right] + right_s
if hash_left == hash_right:
if left_s == right_s:
best = left_s
left += 1
right -= 1
return best
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
ans = ''
l, r = 0, 0
mod = 10**9 + 7
for i in range(len(s) - 1):
l = (l * 31 + ord(s[i])) % mod
r = (r + ord(s[len(s) - i - 1]) * pow(31, i, mod)) % mod
if l == r:
ans = s[:i + 1]
return ans
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, st: str) -> str:
a = st
l = len(a)
leng = 0
lps = [0]
i = 1
while i < l:
if a[i] == a[leng]:
leng += 1
lps.append(leng)
i += 1
else:
if leng > 0:
leng = lps[leng - 1]
else:
lps.append(0)
i += 1
return st[:lps[-1]]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
ans = ''
l, r = 0, 0
mod = 10**9 + 7
for i in range(len(s) - 1):
l = (l * 31 + ord(s[i])) % mod
r = (r + ord(s[len(s) - i - 1]) * pow(31, i, mod)) % mod
if l == r and s[: i + 1] == s[len(s) - i - 1:]:
ans = s[:i + 1]
return ans
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
ls = len(s)
id = -1
for i in range(ls-1):
if s[0:i+1] == s[ls-i-1:ls]:
id = i
return s[:id+1]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
ans = 0
for l in range(len(s)):
if s[:l] == s[-l:]:
ans = l
return s[:ans]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
max_index = -1
for index, _ in enumerate(s[:-1]):
if s[:index+1] == s[-1*(index+1):]:
max_index = index
return s[:max_index+1]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
i,j,l=0,1,len(s)
m=0
while(i<l-1):
if(s[0:i+1]==s[l-i-1: ]):
m=i+1
#print(\"i=\",i,s[0:i+1],\" \",s[l-i-1: ])
i+=1
if(m==l-1):
return s[ :l-1]
else:
return s[0:m]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
solution = ''
for i in range(len(s)):
prefix = s[0:i]
suffix = s[-len(prefix):]
if prefix == suffix:
solution = prefix
return solution
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
if len(s) < 2:
return ''
length = len(s)
res = ''
for i in range(len(s) - 1):
if s[ : i + 1] == s[length - i - 1 : ]:
res = s[ : i + 1]
return res
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
answer = ''
for n in range(1,len(s)):
prefix = s[:n]
suffix = s[-n:]
if prefix == suffix:
answer = prefix
return answer
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
long = 0
for x in range(0,len(s)-1):
# print(s[0:x+1] ,s[len(s)-1-x:])
# print(s[0:x+1]==s[len(s)-1-x:])
if s[0:x+1]==s[len(s)-1-x:]:
long = max(long, len(s[0:x+1]))
# print(long)
return s[:long]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
res = ''
i, j = 0, len(s) - 1
while i < len(s)-1:
if s[:i+1] == s[j:]:
res = s[:i+1]
i += 1
j -= 1
return res
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
#KMP
lps = [0] * len(s)
j = 0
for i in range(1, len(s)):
while j > 0 and s[j] != s[i]:
j = lps[j - 1]
if s[j] == s[i]:
lps[i] = j + 1
j += 1
return s[:lps[-1]]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
long = 0
for x in range(0,len(s)-1):
a = s[0:x+1]
b = s[len(s)-1-x:]
if a==b:
long = max(long, len(a))
return s[:long]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
long = 0
for x in range(0,len(s)-1):
if s[0:x+1]==s[len(s)-1-x:]:
long = max(long, len(s[0:x+1]))
return s[:long]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
i=0
string=str()
ans=0
j=len(s)-1
while i<len(s)-1 and j>0:
if s[0:i+1]==s[j:len(s)]:
if i+1>ans:
ans=i+1
string=s[0:i+1]
i=i+1
j=j-1
return string
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
ans=''
for i in range(len(s)):
if s[:i]==s[-i:] and len(s[:i])>=len(ans):
ans=s[:i]
return ans
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
result = ''
left = 0
right = len(s) - 1
hash_left = 0
hash_right = 0
while left < len(s) - 1 and right > 0:
# hash_left += ord(s[left])
# hash_right += ord(s[right])
# if hash_left == hash_right:
if s[:left + 1] == s[right:]:
result = s[right:]
left += 1
right -= 1
return result
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
# prefixes = []
# for i in range(1, len(s)):
# prefixes.append(s[0:i])
# # print(prefixes)
# suffixes = []
# for i in range(1, len(s)):
# suffixes.append(s[len(s)-i:])
# # print(suffixes)
# common = set(prefixes).intersection(set(suffixes))
# # print(common)
# ans = ''
# for s in common:
# if len(s) > len(ans):
# ans = s
# return ans
i = 1
ans = ''
while i < len(s):
# print(s[0:i], s[len(s)-i:])
if s[0:i] == s[len(s)-i:]:
ans = s[0:i]
i += 1
return ans
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
# n = len(s)
# r = -1
# i = 0
# while i < (n-1):
# if s[0:(i+1)] == s[(n-i-1):]:
# r = i
# i += 1
# if i >= (n-1):
# break
# return s[0:(r+1)]
res, l, r, mod = 0, 0, 0, 10**9 + 7
# now we start from the beginning and the end of the string
# note you shouldn't search the whole string! because the longest prefix and suffix is the string itself
for i in range(len(s) - 1):
# based on an idea that is similar to prefix sum, we calculate the prefix hash in O(1) time.
# specifically, we multiply the current prefix by 128 (which is the length of ASCII, but you can use another value as well)
# then add in the ASCII value of the upcoming letter
l = (l * 128 + ord(s[i])) % mod
# similarly, we can calculate the suffix hash in O(1) time.
# Specifically, we get the ith letter from the end using s[~i], note ~i is -i-1
# we find the pow(128, i, mod) and multiply by the letter's ASCII value
# Actually, if we don't care about the beautifulness of the code, you can have a variable to keep track of pow(128, i, mod) as you increase i
r = (r + pow(128, i, mod) * ord(s[~i])) % mod
# we check if the prefix and suffix agrees, if yes, we find yet another longer prefix, so we record the index
if l == r: res = i + 1
# after we finish searching the string, output the prefix
return s[:res]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
n = len(s)
i = 0
maxi = ''
while i<n:
print()
if s[:i] == s[n-i:]:
maxi = max(maxi, s[:i])
i += 1
print('maxi', maxi)
return maxi
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
best = ''
for i in range(1, len(s)):
pattern = s[:i]
if s.startswith(pattern) and s.endswith(pattern):
best = pattern
return best
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
n = len(list(s))
for i in range(0,n):
if s[0:i] == s[n-i:n]:
result = s[0:i]
return result
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class KMP:
def Build(self, p):
m = len(p)
nxt = [0, 0]
j = 0
for i in range(1, m):
while j > 0 and p[i] != p[j]:
j = nxt[j]
if p[i] == p[j]:
j += 1
nxt.append(j)
return nxt
def Match(self, s, p):
n = len(s)
m = len(p)
nxt = self.Build(p)
ans = []
j = 0
for i in range(n):
while j > 0 and s[i] != p[j]:
j = nxt[j]
if s[i] == p[j]:
j += 1
if j == m:
ans.append(i - m + 1)
j = nxt[j]
return ans
class Solution:
def longestPrefix(self, s: str) -> str:
kmp = KMP()
nxt = kmp.Build(s)
return s[:nxt[-1]]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
len_s = len(s)
nxts = [0] * len_s
i, j = 1, 0
while i < len_s:
while s[j] != s[i] and j > 0:
j = nxts[j - 1] # 退而求其次 考虑 s[:j - 1], 这个算过了是nxt(s[j - 1])
if s[j] == s[i]: # while stop only two
j = j + 1
nxts[i] = j
i = i + 1
return s[len_s-nxts[-1]:]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
pre = self.get_pre(s)
return s[0:pre[-1]]
def get_pre(self, pattern):
pre = [0]
n = len(pattern)
j = 0
for i in range(1, n):
while j and pattern[j] != pattern[i]:
j = pre[j-1]
if pattern[i] == pattern[j]:
j +=1
pre.append(j)
return pre
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
len_s = len(s)
nxts = [0] * len_s
i = 1
j = 0
while i < len_s:
while j > 0 and s[j] != s[i]:
j = nxts[j - 1] # 退而求其次 考虑 s[:j - 1], 这个算过了是nxt(s[j - 1])
if s[j] == s[i]: # while stop only two
j = j + 1
nxts[i] = j
i = i + 1
return s[len_s-nxts[-1]:]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
n = len(s)
arr = [0 for i in range(n)]
i = 1
j = 0
try:
while i<n:
if j==0 and s[i]!=s[j]:
arr[i] = 0
i+=1
else:
if s[i]==s[j]:
arr[i] = j+1
i+=1
j+=1
else:
j = arr[j-1]
return s[:arr[n-1]]
except:
return i
'''
a a b a a b a a a
0 1 2 3 4 5 6 7 8
0 1 0 1 2 3 4 5 2
'''
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
n = len(s)
lps = [0]*n
for i in range(1, n):
j = lps[i-1]
while j>0 and s[j]!=s[i]:
j = lps[j-1]
if s[j]==s[i]:
lps[i] = j+1
return s[:lps[n-1]]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
def build(p):
m = len(p)
nxt = [0,0]
j = 0
for i in range(1,m):
while j > 0 and s[i] != s[j]:
j = nxt[j]
if s[i] == s[j]:
j += 1
nxt.append(j)
return nxt
nxt = build(s)
return s[:nxt[-1]]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
len_s = len(s)
nxts = [0]
i = 1
j = 0
while i < len_s:
while j > 0 and s[j] != s[i]:
j = nxts[j - 1] # 退而求其次 考虑 s[:j - 1], 这个算过了是nxt(s[j - 1])
if s[j] == s[i]:
j = j + 1
i = i + 1
nxts.append(j)
return s[len_s-nxts[-1]:]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
len_s = len(s)
nxts = [0]
i = 1
j = 0
while i < len_s:
while j > 0 and s[j] != s[i]:
j = nxts[j - 1] # 退而求其次
if s[j] == s[i]:
j = j + 1
else:
j = 0
i = i + 1
nxts.append(j)
return s[len_s-nxts[-1]:]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
l = len(s)
nx = [-1] * (l + 1)
i, j = 0, -1
while i < l:
while j == -1 or (i < l and s[i] == s[j]):
i += 1
j += 1
nx[i] = j
if i < l and s[i] != s[j]: j = nx[j]
return s[:nx[-1]]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
i, j = 0, -1
t = [0 for _ in range(len(s)+1)]
t[0] = -1
while i < len(s):
if j == -1 or s[i] == s[j]:
i += 1
j += 1
t[i] = j
else:
j = t[j]
return s[:t[-1]]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
def build():
hashtable = [0 for _ in s]
for i in range(1, len(s)):
j = hashtable[i - 1]
while j > 0 and s[i] != s[j]:
j = hashtable[j - 1]
if s[i] == s[j]:
hashtable[i] = j + 1
return hashtable
table = build()
return s[len(s) - table[-1]:]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
par = [0] * len(s)
for i in range(1, len(s)):
j = par[i-1]
while j and s[j] != s[i]:
j = par[j-1]
j += int(s[i] == s[j])
par[i] = j
return s[:par[-1]]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
n = len(s)
pi = [0]*n
for i in range(1, n):
j = pi[i - 1]
while j > 0 and s[j] != s[i]:
j = pi[j - 1]
if s[i] == s[j]:
j += 1
pi[i] = j
return s[:pi[n-1]]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
lps = [0]
for i in range(1, len(s)):
pos = lps[-1]
if s[pos] == s[i]:
lps.append(1+lps[-1])
else:
pos = lps[lps[-1]-1]
if s[pos] == s[i]:
lps.append(1+pos)
else:
lps.append(0)
return s[:lps[-1]]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, st: str) -> str:
a=st
l=len(a)
leng=0
i=1
lps=[0]
while i<l:
if a[leng]==a[i]:
leng+=1
lps.append(leng)
i+=1
else:
if leng>0:
leng=lps[leng-1]
else:
lps.append(0)
i+=1
return st[:lps[-1]]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
n=len(s)
LPS=[0]*n
i=1
longestprefix=0
while i<n:
if s[longestprefix]==s[i]:
longestprefix+=1
LPS[i]=longestprefix
i+=1
else:
if longestprefix>0:
longestprefix=LPS[longestprefix-1]
else:
i+=1
return s[:LPS[-1]]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
lps=[0]*len(s)
i=1
l=0
while(i<len(s)):
if(s[i]==s[l]):
l=l+1
lps[i]=l
i=i+1
else:
if(l):
l=lps[l-1]
else:
lps[i]=0
i=i+1
m=lps[-1]
index=len(s)-1
#print(lps)
#for i in range(len(s)):
# if(lps[i]>m):
# m=lps[i]
# index=i
#print(m,index)
return s[abs(m-index-1):index+1]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
t = [-1]
pos, cnd = 1, 0
while pos < len(s)-1:
if s[pos] == s[cnd]:
t.append(t[cnd])
else:
t.append(cnd)
cnd = t[cnd]
while cnd >= 0 and s[pos] != s[cnd]:
cnd = t[cnd]
pos += 1
cnd += 1
t.append(cnd)
j, k = 1, 0
while j < len(s):
if s[k] == s[j]:
j += 1
k += 1
if k == len(s):
k = t[k]
else:
k = t[k]
if k < 0:
j += 1
k += 1
return s[:k]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
n = len(s)
prefix, suffix = 0, 0
base, mod, mul = 31, 1000000007, 1
happy = 0
for i in range(1, n):
prefix = (prefix * base + (ord(s[i - 1]) - 97)) % mod
suffix = (suffix + (ord(s[n - i]) - 97) * mul) % mod
if prefix == suffix:
happy = i
mul = mul * base % mod
return s[:happy]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
MOD = 100000007
class Solution:
def longestPrefix(self, s: str) -> str:
r = 0
L = R = 0
multi = 1
for i in range(len(s)-1):
L = (26*L + ord(s[i]) - ord('a')) % MOD
R = ((ord(s[~i]) - ord('a')) * multi + R) % MOD
multi = multi * 26 % MOD
if L == R:
r = i + 1
return s[:r]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
n = len(s)
if(n < 2):
return ''
i = 1; j = 0
f = [0 for _ in range(n)]
while(i < n):
if(s[i] == s[j]):
j += 1
f[i] = j
i += 1
elif(j > 0):
j = f[j - 1]
else:
i += 1
return s[:f[-1]]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
n = len(s)
for i in range(1, n):
if s.startswith(s[i:]):
return s[i:]
return ''
class Solution2:
def longestPrefix(self, s: str) -> str:
n = len(s)
dp = [[ 0 ] * n for _ in range(n)]
for i in range(n - 1):
for j in range(i +1, n):
if s[i] == s[j]:
if i == 0:
dp[i][j] = 1
elif dp[i-1][j - 1]:
dp[i][j] = dp[i-1][j - 1] + 1
max_len = 0
for i in range(n): max_len = max(max_len, dp[i][n-1])
return s[-max_len:] if max_len else ''
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
# rolling hash
# use large prime as hash function, pay attention to the possible hash collision.
# fibonacci primes: 2, 3, 5, 13, 89, 233, 1597, 28657, 514229, 433494437, 2971215073,
# 99194853094755497, 1066340417491710595814572169, 19134702400093278081449423917, ..
M = 19134702400093278081449423917
n, h, t = len(s), 0, 0
v = list(map(lambda x: ord(x) - ord('a'), s))
l, p = 0, 1
for i in range(n - 1):
h = (h * 26 + v[i]) % M
t = (v[n - 1 - i] * p + t) % M
p = p * 26 % M
if h == t:
l = i + 1
return s[:l]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
MOD = 10 ** 9 + 7
def longestPrefix(self, s: str) -> str:
N = len(s)
left_i, right_i = 0, N - 1
left_val = right_val = 0
best_left = -1
right_multiplier = 1
for i in range(N - 1):
left_char, right_char = s[i], s[N-i-1]
left_val = left_val * 26 + (ord(left_char) - ord('a'))
right_val = (ord(right_char) - ord('a')) * right_multiplier + right_val
right_multiplier *= 26
left_val %= Solution.MOD
right_val %= Solution.MOD
right_multiplier %= Solution.MOD
if left_val == right_val:
best_left = i
return s[:best_left+1]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
if len(s) == 1: return ''
def KMPSearch(pat, txt):
M, N = len(pat), len(txt)
lps = failure(pat)
i = 0 # index for txt[]
j = 0 # index for pat[]
while i < N:
if pat[j] == txt[i]:
i += 1
j += 1
elif i < N and pat[j] != txt[i]:
if j != 0:
j = lps[j-1]
else:
i += 1
if i >= N:
return i - j
def failure(pat):
res = [0]
i, target = 1, 0
while i < len(pat):
if pat[i]== pat[target]:
target += 1
res += target,
i += 1
elif target:
target = res[target-1]
else:
res += 0,
i += 1
return res
l = len(s) - 1 - KMPSearch(s[:-1], s[1:])
return s[:l]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
n=len(s)
if n<=1: return ''
prefix, suffix,base=0,0,1
NUM=10**9+7
ans=''
for i in range(1,n):
# i is the length of prefix and suffix
x=ord(s[i-1])-ord('a')
prefix=(26*prefix+x) % NUM
x=ord(s[n-i])-ord('a')
suffix=(suffix+x*base) % NUM
base=(base*26) % NUM
if prefix==suffix:
if s[0:i]==s[n-i:n]: ans=s[0:i]
return ans
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
result = ''
left = 0
right = len(s) - 1
hash_left = 0
hash_right = 0
while left < len(s) - 1 and right > 0:
hash_left += ord(s[left])
hash_right += ord(s[right])
if hash_left == hash_right:
if s[:left + 1] == s[right:]:
result = s[right:]
left += 1
right -= 1
return result
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
# https://leetcode.com/problems/longest-happy-prefix/discuss/547237/JavaPython-Rolling-Hash
# https://leetcode.com/problems/longest-happy-prefix/discuss/547446/C%2B%2BJava-with-picture-incremental-hash-and-KMP
n = len(s)
prefix = [0]*n
j, i = 0, 1
while i < n:
if s[j] == s[i]:
j += 1
prefix[i] = j
elif j > 0:
j = prefix[j-1]
i -= 1
i += 1
return s[:j]
|
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters.
|
class Solution:
def longestPrefix(self, s: str) -> str:
best = ''
left = 0
right = len(s) - 1
hash_left = 0
hash_right = 0
while left < len(s) - 1 and right > 0:
hash_left += ord(s[left])
hash_right += ord(s[right])
if hash_left == hash_right:
if s[:left + 1] == s[right:]:
best = s[right:]
left += 1
right -= 1
return best
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.