← Home
package main

import (
	"io"
	"os"
)

func main() {
	input, _ := io.ReadAll(os.Stdin)
	pos := 0

	readInt := func() int {
		for pos < len(input) && (input[pos] < '0' || input[pos] > '9') {
			pos++
		}
		if pos >= len(input) {
			return 0
		}
		res := 0
		for pos < len(input) && input[pos] >= '0' && input[pos] <= '9' {
			res = res*10 + int(input[pos]-'0')
			pos++
		}
		return res
	}

	readBytes := func() []byte {
		for pos < len(input) && input[pos] <= ' ' {
			pos++
		}
		if pos >= len(input) {
			return nil
		}
		start := pos
		for pos < len(input) && input[pos] > ' ' {
			pos++
		}
		return input[start:pos]
	}

	n := readInt()
	if n == 0 {
		return
	}
	s := readBytes()
	q := readInt()

	var ans [26][1505]int

	for c := 0; c < 26; c++ {
		char := byte(c + 'a')
		for L := 0; L < n; L++ {
			changes := 0
			for R := L; R < n; R++ {
				if s[R] != char {
					changes++
				}
				if R-L+1 > ans[c][changes] {
					ans[c][changes] = R - L + 1
				}
			}
		}
		for i := 1; i <= n; i++ {
			if ans[c][i] < ans[c][i-1] {
				ans[c][i] = ans[c][i-1]
			}
		}
	}

	out := make([]byte, 0, q*10)
	for i := 0; i < q; i++ {
		m := readInt()
		for pos < len(input) && input[pos] <= ' ' {
			pos++
		}
		char := input[pos]
		pos++

		if m > n {
			m = n
		}

		v := ans[char-'a'][m]
		if v == 0 {
			out = append(out, '0', '\n')
		} else {
			var tmp [10]byte
			idx := 10
			for v > 0 {
				idx--
				tmp[idx] = byte(v%10) + '0'
				v /= 10
			}
			out = append(out, tmp[idx:]...)
			out = append(out, '\n')
		}
	}
	os.Stdout.Write(out)
}