Ruby sliding window solution


  • 0
    B
    def check_inclusion(s1, s2)
        map1 = Hash.new{|h,k| h[k] = 0 }
        map2 = Hash.new{|h,k| h[k] = 0 }
        k = s1.size
        s1.chars.each do |ch|
            map1[ch] += 1
        end
        #make sliding window
        (0...k).each do |i|
            map2[s2[i]] += 1
        end
        return true if map1 == map2
        #update window
        (k...s2.size).each do |i|
            map2[s2[i]] += 1
            map2[s2[i-k]] -= 1
            map2.delete(s2[i-k]) if map2[s2[i-k]] == 0
            return true if map1 == map2
        end
        return false
    end
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.