這題跟昨天的原理一樣,就不多說了。 DAY17
class Solution: def checkInclusion(self, s1: str, s2: str) -> bool: count = Counter(s1) match_len = 0 p_len = len(s1) for i, c in enumerate(s2): while match_len and (c not in count or count[c] == 0): count[s2[i - match_len]] += 1 match_len -= 1 if c in count and count[c] > 0: match_len += 1 count[c] -= 1 if match_len == p_len: return True return False
C#
public class Solution { public bool CheckInclusion(string s1, string s2) { var count = new int[26]; foreach(char c in s1) { count[c - 'a'] += 1; } int match_len = 0; for(int i = 0; i < s2.Length; i++) { char c = s2[i]; while(match_len > 0 && count[c - 'a'] == 0) { count[s2[i - match_len] - 'a'] += 1; match_len -= 1; } if(count[c - 'a'] > 0) { match_len += 1; count[c - 'a'] -= 1; if(match_len == s1.Length) { return true; } } } return false; } }