Medium
,String
,Hash Table
,Two Pointers
,Sliding Window
Given two strings s1
and s2
, return true
if s2
contains a permutation of s1
, or false
otherwise.
In other words, return true
if one of s1
's permutations is the substring of s2
.
Example 1:
Example 2:
Constraints:
s1.length
, s2.length
<= 104s1
and s2
consist of lowercase English letters.Yen-Chi ChenSat, Feb 4, 2023
Yen-Chi ChenSat, Feb 4, 2023
一開始耍腦殘把s1
的字母所有排列組合都列出來然後丟到s2
去比對。
其實不用管s1
的組合,只要找s2
中相同長度的子字串,其中有s1
的所有字母且各字母數一樣即可。
例:
s1 = aabc
s2 = bacadbe
s2
的子字串中只要符合長度與s1
相同且有2個a
、1個b
、1個c
,那就一定是s1
的排列組合之一。
s1
中各字母出現的次數(s1Map
)s2
,尋找長度為s1.length
的子字串,並記錄各字母出現的次數(s2Map
)s1Map
與s2Map
中各字母出現的次數是否相同使用slinding window就不用每次都重新計算s2Map
,只要把最左邊的字母刪掉,再把最右邊的字母加進去即可。
寫完還是看不懂吉神寫的,怎麼可以這麼簡潔…
MarsgoatFeb 16, 2023
吉神教學版
吉神:我們其實只需要用一個s1大小的sliding window在s2上掃過去就好
感恩彥吉大神教學
MarsgoatFeb 16, 2023