2020年5月18日 星期一

Leetcode題解 Python & C#:五月挑戰DAY18 Permutation in String

給二字串 s1 s2,問 s2 是否有含 s1 的排列。

這題跟昨天的原理一樣,就不多說了。 DAY17

Python
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;
    }
}