76 最小覆蓋子串

2021-10-01 07:59:44 字數 2709 閱讀 3597

"""

題目:給你乙個字串s、乙個字串t,請在字串s裡面找出:包含t所有字母的最小子串。

示例:輸入:s="adobecodebanc", t="abc

輸出:"banc"

"""# 方法一 自己寫的,但是leetcode上超時

defminwindow

(s, t)

: m =

0 all_in =

false

iflen

(t)==0or

len(s)==0

:return

""if

len(t)

>

len(s)

:return

"" minlength =

len(t)

str=

while

true

:for i in

range

(len

(s)-minlength+1)

: left = i

right = i + minlength

for k in s[left:right]

:str

for j in

range

(len

(t))

:for n in

range

(len

(str))

:if t[j]

==str

[n]:

m +=

1str

.pop(n)

break

if m ==

len(t)

: all_in =

true

str=

m =0if all_in:

return s[left:right]

minlength +=

1if minlength ==

len(s)+1

:return

""print

(minwindow(

"adobecodebanc"

,"r"))

print

(minwindow(

"acbbaca"

,"aba"))

# 方法二 leetcode上的官方解法

from collections import counter

defminwindow

(s, t):if

not t or

not s:

return

"" dict_t = counter(t)

required =

len(dict_t)

# t中不重複元素的個數

filtered_s =

# t中元素在s**現的情況(位置, 值)

for i, char in

enumerate

(s):

if char in dict_t:

(i, char)

) l, r =0,

0 formed =

0 window_counts =

ans =

float

("inf"),

none

,none

while r <

len(filtered_s)

: character = filtered_s[r][1

] window_counts[character]

= window_counts.get(character,0)

+1if window_counts[character]

== dict_t[character]

: formed +=

1# 直到t**現的元素在滑動視窗中全有, 否則一直擴大滑動視窗

while l <= r and formed == required:

# 判斷視窗是否可以縮小,left右移

character = filtered_s[l][1

] end = filtered_s[r][0

] start = filtered_s[l][0

]if end - start +

1< ans[0]

: ans =

(end - start +

1, start, end)

window_counts[character]-=1

if window_counts[character]

< dict_t[character]

: formed -=

1 l +=

1 r +=

1return

""if ans[0]

==float

("inf"

)else s[ans[1]

:ans[2]

+1]# print(minwindow("adobecodebanc", "abc"))

print

(minwindow(

"acbbccd"

,"ad"

))

76 最小覆蓋子串

給你乙個字串 s 乙個字串 t,請在字串 s 裡面找出 包含 t 所有字母的最小子串。示例 輸入 s adobecodebanc t abc 輸出 banc 說明 如果 s 中不存這樣的子串,則返回空字串 如果 s 中存在這樣的子串,我們保證它是唯一的答案。class solution int ma...

76最小覆蓋子串

給你乙個字串 s 乙個字串 t,請在字串 s 裡面找出 包含 t 所有字母的最小子串。示例 輸入 s adobecodebanc t abc 輸出 banc 說明 滑動視窗解法。hashmap方式 param s param t return public static string minwind...

76 最小覆蓋子串

給你乙個字串 s 乙個字串 t,請在字串 s 裡面找出 包含 t 所有字元的最小子串。示例 輸入 s adobecodebanc t abc 輸出 banc 說明 如果 s 中不存這樣的子串,則返回空字串 如果 s 中存在這樣的子串,我們保證它是唯一的答案。使用滑動視窗的思想,我們可以用乙個map來...