You are given a string $s$ consisting of lowercase Latin letters "a", "b" and "c" and question marks "?".

Let the number of question marks in the string $s$ be $k$. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all $3^{k}$ possible strings consisting only of letters "a", "b" and "c". For example, if $s = $"ac?b?c" then we can obtain the following strings: $[$"acabac", "acabbc", "acabcc", "acbbac", "acbbbc", "acbbcc", "accbac", "accbbc", "accbcc"$]$.

Your task is to count the total number of subsequences "abc" in all resulting strings. Since the answer can be very large, print it modulo $10^{9} + 7$.

A subsequence of the string $t$ is such a sequence that can be derived from the string $t$ after removing some (possibly, zero) number of letters without changing the order of remaining letters. For example, the string "baacbc" contains two subsequences "abc" — a subsequence consisting of letters at positions $(2, 5, 6)$ and a subsequence consisting of letters at positions $(3, 5, 6)$.


-----Input-----

The first line of the input contains one integer $n$ $(3 \le n \le 200\,000)$ — the length of $s$.

The second line of the input contains the string $s$ of length $n$ consisting of lowercase Latin letters "a", "b" and "c" and question marks"?".


-----Output-----

Print the total number of subsequences "abc" in all strings you can obtain if you replace all question marks with letters "a", "b" and "c", modulo $10^{9} + 7$.


-----Examples-----
Input
6
ac?b?c

Output
24

Input
7
???????

Output
2835

Input
9
cccbbbaaa

Output
0

Input
5
a???c

Output
46



-----Note-----

In the first example, we can obtain $9$ strings:  "acabac" — there are $2$ subsequences "abc",  "acabbc" — there are $4$ subsequences "abc",  "acabcc" — there are $4$ subsequences "abc",  "acbbac" — there are $2$ subsequences "abc",  "acbbbc" — there are $3$ subsequences "abc",  "acbbcc" — there are $4$ subsequences "abc",  "accbac" — there is $1$ subsequence "abc",  "accbbc" — there are $2$ subsequences "abc",  "accbcc" — there are $2$ subsequences "abc". 

So, there are $2 + 4 + 4 + 2 + 3 + 4 + 1 + 2 + 2 = 24$ subsequences "abc" in total.

Difficulty: HARD
Tags: String algorithms

Combinatorics

Dynamic programming
Skill types: Dynamic programming

Starter code:

Solutions:
def solve(s, n):
	a = 0
	ab = 0
	abc = 0
	aTimes = 1
	for i in range(s):
		if n[i] == 'a':
			a += aTimes
			a = a % mod
		elif n[i] == 'b':
			ab += a
			ab = ab % mod
		elif n[i] == 'c':
			abc += ab
			abc = abc % mod
		elif n[i] == '?':
			abc = (3 * abc + ab) % mod
			ab = (3 * ab + a) % mod
			a = (3 * a + aTimes) % mod
			aTimes = aTimes * 3 % mod
	return abc
mod = 10 ** 9 + 7
s = int(input())
n = input()
print(solve(s, n))


n = int(input())
seq = input()
a = 0
ab = 0
abc = 0
u = 1
d = 10 ** 9 + 7
for i in seq:
	if i == 'a':
		a += u
	elif i == 'b':
		ab += a
	elif i == 'c':
		abc += ab
	else:
		abc = (3 * abc + ab) % d
		ab = (3 * ab + a) % d
		a = (3 * a + u) % d
		u = 3 * u % d
print(abc % (10 ** 9 + 7))


Mod = 10 ** 9 + 7
n = int(input())
s = input()
(cnt, a, ab, abc) = (1, 0, 0, 0)
for i in range(len(s)):
	if s[i] == 'a':
		a += cnt
		a %= Mod
	elif s[i] == 'b':
		ab += a
		ab %= Mod
	elif s[i] == 'c':
		abc += ab
		abc %= Mod
	else:
		abc *= 3
		abc += ab
		abc %= Mod
		ab *= 3
		ab += a
		ab %= Mod
		a *= 3
		a += cnt
		a %= Mod
		cnt *= 3
		cnt %= Mod
print(abc)


import sys
input = sys.stdin.readline

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())
MOD = 1000000000 + 7

def add(n, v):
	return (n + v) % MOD
n = inp()
s = insr()
prev = {'none': 1, 'a': 0, 'ab': 0}
total = 0
for i in range(n):
	curt = prev.copy()
	if s[i] == 'a':
		curt['a'] = add(curt['a'], prev['none'])
	elif s[i] == 'b':
		curt['ab'] = add(curt['ab'], prev['a'])
	elif s[i] == 'c':
		total = add(total, prev['ab'])
	elif s[i] == '?':
		curt['none'] = prev['none'] * 3 % MOD
		curt['a'] = (prev['a'] * 3 + prev['none']) % MOD
		curt['ab'] = (prev['ab'] * 3 + prev['a']) % MOD
		total = (total * 3 + prev['ab']) % MOD
	prev = curt
print(total)


import math
from sys import stdin, stdout

def getInts():
	return list(map(int, stdin.readline().split()))

def getInt():
	return int(input())

def lower_bound(v, x):
	low = 0
	high = len(v) - 1
	ans = len(v)
	while low <= high:
		mid = (low + high) // 2
		if v[mid] < x:
			low = mid + 1
		else:
			ans = mid
			high = mid - 1
	return ans

def upper_bound(v, x):
	low = 0
	high = len(v) - 1
	ans = len(v)
	while low <= high:
		mid = (low + high) // 2
		if v[mid] <= x:
			low = mid + 1
		else:
			ans = mid
			high = mid - 1
	return ans
MOD = 1000000007

def mul(x, y):
	ans = x * y
	if ans > MOD:
		ans = ans % MOD
	if ans < 0:
		ans = ans % MOD
		ans = (ans + MOD) % MOD
	return ans

def add(x, y):
	ans = x + y
	if ans > MOD:
		ans = ans % MOD
	if ans < 0:
		ans = ans % MOD
		ans = (ans + MOD) % MOD
	return ans
n = getInt()
s = stdin.readline()
a = 0
ab = 0
abc = 0
m = 1
for i in range(n):
	if s[i] == 'a':
		a = (a + m) % MOD
	elif s[i] == 'b':
		ab = (ab + a) % MOD
	elif s[i] == 'c':
		abc = (abc + ab) % MOD
	else:
		abc = (3 * abc + ab) % MOD
		ab = (3 * ab + a) % MOD
		a = (3 * a + m) % MOD
		m = 3 * m % MOD
abc = abc % MOD
abc = (abc + MOD) % MOD
print(abc)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
n = int(input())
vals = [k for k in input()]
mod = 10 ** 9 + 7
prefq = [0]
if vals[0] == '?':
	prefq = [1]
for s in range(1, n):
	if vals[s] == '?':
		prefq.append(prefq[-1] + 1)
	else:
		prefq.append(prefq[-1])
abc = 0
ab = 0
a = 0
sfs = 0
for s in range(n):
	if vals[s] == 'a':
		a += pow(3, sfs, mod)
	elif vals[s] == 'b':
		ab += a
	elif vals[s] == 'c':
		abc += ab
	else:
		abc = 3 * abc + ab
		ab = 3 * ab + a
		a = 3 * a + pow(3, sfs, mod)
		sfs += 1
	abc = abc % mod
	ab = ab % mod
	a = a % mod
print(abc)


MOD = 10 ** 9 + +7

def performModulo(i, nAs, nABs, nABCs):
	nAs[i] %= MOD
	nABs[i] %= MOD
	nABCs[i] %= MOD
	return

def main():
	n = int(input())
	s = input()
	nAs = [0 for _ in range(n)]
	nABs = [0 for _ in range(n)]
	nABCs = [0 for _ in range(n)]
	m = 1
	for (i, c) in enumerate(s):
		if i - 1 >= 0:
			nAs[i] += nAs[i - 1]
			nABs[i] += nABs[i - 1]
			nABCs[i] += nABCs[i - 1]
		if c == 'a':
			nAs[i] += m
			performModulo(i, nAs, nABs, nABCs)
		elif c == 'b':
			if i - 1 >= 0:
				nABs[i] += nAs[i - 1]
				performModulo(i, nAs, nABs, nABCs)
		elif c == 'c':
			if i - 1 >= 0:
				nABCs[i] += nABs[i - 1]
				performModulo(i, nAs, nABs, nABCs)
		else:
			tempAs = nAs[i]
			tempABs = nABs[i]
			tempABCs = nABCs[i]
			nAs[i] = tempAs
			nABs[i] = tempABs
			nABCs[i] = tempABCs
			nAs[i] += m
			performModulo(i, nAs, nABs, nABCs)
			nAs[i] += tempAs
			nABs[i] += tempABs
			nABCs[i] += tempABCs
			if i - 1 >= 0:
				nABs[i] += nAs[i - 1]
			performModulo(i, nAs, nABs, nABCs)
			nAs[i] += tempAs
			nABs[i] += tempABs
			nABCs[i] += tempABCs
			if i - 1 >= 0:
				nABCs[i] += nABs[i - 1]
			performModulo(i, nAs, nABs, nABCs)
			m *= 3
			m %= MOD
	ans = nABCs[n - 1]
	print(ans)
	return
import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
main()


n = input()
s = input()
zcolv = 0
for i in s:
	if i == '?':
		zcolv += 1
a = 0
ab = 0
mod = 10 ** 9 + 7
abc = 0
z = 0
zb = 0
az = 0
zz = 0
abz = 0
azc = 0
zbc = 0
azz = 0
zbz = 0
zzc = 0
zzz = 0
for i in s:
	if i == 'a':
		a += 1
	if i == 'b':
		ab += a
		zb += z
		zb %= mod
		ab %= mod
	if i == 'c':
		abc += ab
		zbc += zb
		zzc += zz
		azc += az
		zbc %= mod
		zzc %= mod
		azc %= mod
		abc %= mod
	if i == '?':
		abz += ab
		azz += az
		zbz += zb
		zzz += zz
		zz += z
		az += a
		z += 1
		abz %= mod
		azz %= mod
		zbz %= mod
		zzz %= mod
		zz %= mod
		az %= mod
		z %= mod
print((abc * pow(3, zcolv, mod) + (abz + azc + zbc) * pow(3, max(zcolv - 1, 0), mod) + (azz + zbz + zzc) * pow(3, max(zcolv - 2, 0), mod) + zzz * pow(3, max(zcolv - 3, 0))) % mod)


INF = 1000000007
n = int(input(''))
s = input('')
dp = [[0] * 3] * (n + 1)
a = 1
sol = []
for i in range(1, n + 1):
	d = dp[i - 1][0]
	b = dp[i - 1][1]
	c = dp[i - 1][2]
	if s[i - 1] == 'a':
		dp[i][0] += a
	elif s[i - 1] == 'b':
		dp[i][1] += dp[i - 1][0]
	elif s[i - 1] == 'c':
		dp[i][2] += dp[i - 1][1]
	else:
		dp[i][0] = 3 * d + a
		dp[i][1] = 3 * b + d
		dp[i][2] = 3 * c + b
		a *= 3
	dp[i][0] = dp[i][0] % INF
	dp[i][1] = dp[i][1] % INF
	dp[i][2] = dp[i][2] % INF
	a = a % INF
print(dp[n][2])


n = int(input())
s = input()
a = 0
b = 0
c = 0
v = 1
mod = 10 ** 9 + 7
for i in range(n):
	if s[i] == 'a':
		a += v
	elif s[i] == 'b':
		b += a
	elif s[i] == 'c':
		c += b
	else:
		c = (3 * c + b) % mod
		b = (3 * b + a) % mod
		a = (3 * a + v) % mod
		v = 3 * v % mod
print(c % mod)


n = int(input())
s = input().strip()
(pa, pq, sc, sq) = (0, 0, s.count('c'), s.count('?'))
an = 0
for i in range(n):
	if s[i] == '?':
		sq -= 1
		an += pow(3, pq + sq, 10 ** 9 + 7) * pa * sc
		if pq + sq > 0:
			an += pow(3, pq + sq - 1, 10 ** 9 + 7) * pq * sc
			an += pow(3, pq + sq - 1, 10 ** 9 + 7) * pa * sq
		if pq + sq > 1:
			an += pow(3, pq + sq - 2, 10 ** 9 + 7) * pq * sq
		pq += 1
	elif s[i] == 'b':
		an += pow(3, pq + sq, 10 ** 9 + 7) * pa * sc
		if pq + sq > 0:
			an += pow(3, pq + sq - 1, 10 ** 9 + 7) * pq * sc
			an += pow(3, pq + sq - 1, 10 ** 9 + 7) * pa * sq
		if pq + sq > 1:
			an += pow(3, pq + sq - 2, 10 ** 9 + 7) * pq * sq
	elif s[i] == 'c':
		sc -= 1
	elif s[i] == 'a':
		pa += 1
	an %= 10 ** 9 + 7
print(an)


n = int(input())
s = str(input())
mod = 10 ** 9 + 7
X = [[0] * 4 for _ in range(n + 1)]
for i in range(n):
	for j in range(4):
		X[i + 1][j] = X[i][j]
	if s[i] == 'a':
		X[i + 1][0] += 1
	elif s[i] == 'b':
		X[i + 1][1] += 1
	elif s[i] == 'c':
		X[i + 1][2] += 1
	else:
		X[i + 1][3] += 1
Y = [[0] * 4 for _ in range(n + 1)]
for i in reversed(list(range(n))):
	for j in range(4):
		Y[i][j] = Y[i + 1][j]
	if s[i] == 'a':
		Y[i][0] += 1
	elif s[i] == 'b':
		Y[i][1] += 1
	elif s[i] == 'c':
		Y[i][2] += 1
	else:
		Y[i][3] += 1
c = X[n][3]
ans = 0
for i in range(n):
	if s[i] == 'b':
		ans += X[i + 1][3] * Y[i][3] * pow(3, max(0, c - 2), mod)
		ans += X[i + 1][0] * Y[i][2] * pow(3, c, mod)
		ans += X[i + 1][3] * Y[i][2] * pow(3, max(0, X[i + 1][3] - 1 + Y[i][3]), mod)
		ans += X[i + 1][0] * Y[i][3] * pow(3, max(0, X[i + 1][3] + Y[i][3] - 1), mod)
		ans %= mod
	if s[i] == '?':
		ans += X[i][3] * Y[i + 1][3] * pow(3, max(0, c - 3), mod)
		ans += X[i + 1][0] * Y[i][2] * pow(3, max(0, c - 1), mod)
		ans += X[i][3] * Y[i][2] * pow(3, max(0, X[i][3] - 1 + Y[i + 1][3]), mod)
		ans += X[i + 1][0] * Y[i + 1][3] * pow(3, max(0, X[i][3] + Y[i + 1][3] - 1), mod)
		ans %= mod
		ans %= mod
print(ans)


from sys import stdin, stdout

def number_of_subsequences(n, s):
	MOD = 1000000007
	a_a = [0 for i in range(n + 1)]
	ab_a = [0 for i in range(n + 1)]
	abc_a = [0 for i in range(n + 1)]
	m = 1
	for i in range(1, n + 1):
		if s[i - 1] == 'a':
			a_a[i] = a_a[i - 1] + m
			a_a[i] %= MOD
			ab_a[i] = ab_a[i - 1]
			abc_a[i] = abc_a[i - 1]
		elif s[i - 1] == 'b':
			a_a[i] = a_a[i - 1]
			ab_a[i] = ab_a[i - 1] + a_a[i - 1]
			ab_a[i] %= MOD
			abc_a[i] = abc_a[i - 1]
		elif s[i - 1] == 'c':
			a_a[i] = a_a[i - 1]
			ab_a[i] = ab_a[i - 1]
			abc_a[i] = abc_a[i - 1] + ab_a[i - 1]
			abc_a[i] %= MOD
		else:
			a_a[i] = 3 * a_a[i - 1] + m
			a_a[i] %= MOD
			ab_a[i] = 3 * ab_a[i - 1] + a_a[i - 1]
			ab_a[i] %= MOD
			abc_a[i] = 3 * abc_a[i - 1] + ab_a[i - 1]
			abc_a[i] %= MOD
			m *= 3
			m %= MOD
	return abc_a[n]
n = int(stdin.readline())
s = stdin.readline().strip()
res = number_of_subsequences(n, s)
stdout.write(str(res) + '\n')


import sys
from copy import *
from bisect import *

def eprint(*args):
	print(*args, file=sys.stderr)
zz = 1
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')
di = [[-1, 0], [1, 0], [0, 1], [0, -1]]

def string(s):
	return ''.join(s)

def fori(n):
	return [fi() for i in range(n)]

def inc(d, c, x=1):
	d[c] = d[c] + x if c in d else x

def bo(i):
	return ord(i) - ord('A')

def li():
	return [int(xx) for xx in input().split()]

def fli():
	return [float(x) for x in input().split()]

def comp(a, b):
	if a > b:
		return 2
	return 2 if a == b else 0

def gi():
	return [xx for xx in input().split()]

def fi():
	return int(input())

def pro(a):
	return reduce(lambda a, b: a * b, a)

def swap(a, i, j):
	(a[i], a[j]) = (a[j], a[i])

def si():
	return list(input().rstrip())

def mi():
	return map(int, input().split())

def gh():
	sys.stdout.flush()

def isvalid(i, j):
	return 0 <= i < n and 0 <= j < m and (a[i][j] != '.')

def bo(i):
	return ord(i) - ord('a')

def graph(n, m):
	for i in range(m):
		(x, y) = mi()
		a[x].append(y)
		a[y].append(x)
t = 1

def tri(n, p):
	s = ''
	while n != 0:
		s += str(n % 3)
		n //= 3
	s = s[::-1]
	s = (p - len(s)) * '0' + s
	return s

def brute(s):
	p = 3 ** s.count('?')
	for i in range(p):
		h = tri(i, p)
		r = 'abc'
		l = 0
		for i in range(len(s)):
			if s[i] == '?':
				s

def cil(n, m):
	return n // m + int(n % m > 0)
while t > 0:
	t -= 1
	n = fi()
	mod = 10 ** 9 + 7
	s = si()
	dp = [[0] * 4 for i in range(n + 1)]
	dp[-1][-1] = 1
	for i in range(n):
		dp[i] = deepcopy(dp[i - 1])
		if s[i] == 'a':
			dp[i][0] = (dp[i - 1][-1] + dp[i - 1][0]) % mod
		elif s[i] == 'b':
			dp[i][1] = (dp[i - 1][1] + dp[i - 1][0]) % mod
		elif s[i] == 'c':
			dp[i][2] = (dp[i - 1][2] + dp[i - 1][1]) % mod
		else:
			dp[i][0] = (dp[i - 1][-1] + dp[i - 1][0] * 3) % mod
			dp[i][1] = (dp[i - 1][1] * 3 + dp[i - 1][0]) % mod
			dp[i][2] = (dp[i - 1][2] * 3 + dp[i - 1][1]) % mod
		if s[i] == '?':
			dp[i][-1] = dp[i - 1][-1] * 3 % mod
	c = dp[n - 1][2]
	print(c)


n = int(input())
s = str(input())
a = 0
b = 0
c = 0
d = 0
ans = 0
m = 10 ** 9 + 7
t = 1
for i in s:
	if i == 'a':
		a = (a + t) % m
	elif i == 'b':
		b = (b + a) % m
	elif i == 'c':
		ans = (ans + b) % m
	else:
		ans = (3 * ans + b) % m
		b = (a + 3 * b) % m
		a = (3 * a + t) % m
		t = t * 3 % m
print(ans % m)


n = int(input())
s = input()
ret = 0
Mod = int(1000000000.0 + 7)
dp = [0, 0, 0]
cnt = 1
for i in range(n):
	if s[i] == 'a':
		dp[0] += cnt
	elif s[i] == 'b':
		dp[1] += dp[0]
	elif s[i] == 'c':
		dp[2] += dp[1]
	else:
		dp[2] = (3 * dp[2] + dp[1]) % Mod
		dp[1] = (3 * dp[1] + dp[0]) % Mod
		dp[0] = (3 * dp[0] + cnt) % Mod
		cnt = cnt * 3 % Mod
print(dp[2] % Mod)


n = int(input())
s = input()
numab = 0
numa = 0
res = 0
kol_s = 1
m = 10 ** 9 + 7
for x in s:
	if x == 'a':
		numa += kol_s
	if x == 'b':
		numab += numa
	if x == 'c':
		res += numab
	if x == '?':
		res *= 3
		res += numab
		numab *= 3
		numab += numa
		numa *= 3
		numa += kol_s
		kol_s *= 3
	numa %= m
	numab %= m
	res %= m
	kol_s %= m
print(res)


n = int(input())
s = input()
MOD = 10 ** 9 + 7
aCount = 0
abCount = 0
abcCount = 0
qCount = 0
for elem in s:
	if elem == 'c' or elem == '?':
		abcCount += abCount
		if elem == 'c':
			abcCount += 2 * abCount
	if elem == 'b' or elem == '?':
		abCount += aCount
		if elem == 'b':
			abCount += 2 * aCount
	if elem == 'a' or elem == '?':
		aCount += 1
		if elem == 'a':
			aCount += 2
	if elem == '?':
		qCount += 1
print(abcCount * 3 ** qCount // 27 % MOD)


import sys
input = sys.stdin.readline
n = int(input())
s = input()[:-1]
dp = [[0] * 4 for _ in range(n + 1)]
dp[0][0] = 1
MOD = 10 ** 9 + 7
for i in range(n):
	if s[i] != '?':
		dp[i + 1][0] = dp[i][0]
		dp[i + 1][1] = (dp[i][1] + (dp[i][0] if s[i] == 'a' else 0)) % MOD
		dp[i + 1][2] = (dp[i][2] + (dp[i][1] if s[i] == 'b' else 0)) % MOD
		dp[i + 1][3] = (dp[i][3] + (dp[i][2] if s[i] == 'c' else 0)) % MOD
	else:
		dp[i + 1][0] = 3 * dp[i][0] % MOD
		dp[i + 1][1] = (dp[i][0] + 3 * dp[i][1]) % MOD
		dp[i + 1][2] = (dp[i][1] + 3 * dp[i][2]) % MOD
		dp[i + 1][3] = (dp[i][2] + 3 * dp[i][3]) % MOD
print(dp[n][3])


input()
a = b = c = 0
p = 1
m = 10 ** 9 + 7
for i in input():
	if i == 'a':
		a += p
	elif i == 'b':
		b += a
	elif i == 'c':
		c += b
	else:
		(a, b, c, p) = ((a * 3 + p) % m, (b * 3 + a) % m, (c * 3 + b) % m, p * 3 % m)
print(c % m)


MOD = 10 ** 9 + 7
n = int(input())
A = input()
result = 0
(B, C) = ({}, {})
for x in '?abc':
	B[x] = 0
	C[x] = A.count(x)
for x in A:
	if x == '?' or x == 'b':
		qm = 0 if x != '?' else 1
		left = B['a'] * pow(3, B['?'], MOD) % MOD
		if B['?'] > 0:
			left = (left + B['?'] * pow(3, B['?'] - 1, MOD)) % MOD
		right = (C['c'] - B['c']) * pow(3, C['?'] - B['?'] - qm, MOD) % MOD
		if C['?'] - B['?'] - qm > 0:
			right = (right + (C['?'] - B['?'] - qm) * pow(3, C['?'] - B['?'] - 1 - qm, MOD)) % MOD
		result = (result + left * right) % MOD
	B[x] += 1
print(result)


import math
import sys
from sys import stdin, stdout
ipi = lambda : int(stdin.readline())
ipil = lambda : map(int, stdin.readline().split())
ipf = lambda : float(stdin.readline())
ipfl = lambda : map(float, stdin.readline().split())
ips = lambda : stdin.readline().rstrip()
out = lambda x: stdout.write(str(x) + '\n')
outl = lambda x: print(*x)
n = ipi()
s = ips()
a_cnt = 0
ab_cnt = 0
qst_cnt = 0
ans = 0
mod = int(1000000000.0 + 7)
for i in range(n):
	if s[i] == 'a':
		a_cnt += pow(3, qst_cnt, mod)
	elif s[i] == 'b':
		ab_cnt += a_cnt
	elif s[i] == 'c':
		ans += ab_cnt
	else:
		ans *= 3
		ans += ab_cnt
		ab_cnt *= 3
		ab_cnt += a_cnt
		a_cnt *= 3
		a_cnt += pow(3, qst_cnt, mod)
		qst_cnt += 1
	a_cnt %= mod
	ab_cnt %= mod
	ans %= mod
print(ans)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def print_list(l):
	print(' '.join(map(str, l)))
n = N()
res = 0
s = input()
a = 0
c = s.count('c')
k = s.count('?')
m = 0
M = 1000000007
if k == 0:
	(k0, k1, k2, k3) = (1, 0, 0, 0)
elif k == 1:
	(k0, k1, k2, k3) = (3, 1, 0, 0)
elif k == 2:
	(k0, k1, k2, k3) = (9, 3, 1, 0)
else:
	k3 = 1
	for _ in range(k - 3):
		k3 *= 3
		k3 %= M
	k2 = k3 * 3 % M
	k1 = k2 * 3 % M
	k0 = k1 * 3 % M
(n0, n1, n2, n3) = (0, 0, 0, 0)
for t in s:
	if t == 'a':
		a += 1
	elif t == 'c':
		c -= 1
	elif t == 'b':
		n0 += a * c
		n0 %= M
		n1 += m * c + a * (k - m)
		n1 %= M
		n2 += m * (k - m)
		n2 %= M
	else:
		n1 += a * c
		n1 %= M
		n2 += m * c + a * (k - m - 1)
		n2 %= M
		n3 += m * (k - m - 1)
		n3 %= M
		m += 1
print((n0 * k0 + n1 * k1 + n2 * k2 + n3 * k3) % M)


import sys
input = sys.stdin.readline

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input().strip()

def listStr():
	return list(input().strip())
import collections as col
M = 10 ** 9 + 7

def solve():
	N = getInt()
	S = listStr()
	dp = [[1, 0, 0, 0]]
	ref = {'a': 1, 'b': 2, 'c': 3}
	for s in S:
		tmp = list(dp[-1])
		if s == '?':
			for i in range(4):
				tmp[i] *= 3
				tmp[i] %= M
			for i in range(1, 4):
				tmp[i] += dp[-1][i - 1]
				tmp[i] %= M
		else:
			x = ref[s]
			tmp[x] += dp[-1][x - 1]
			tmp[x] %= M
		dp.append(tmp)
	return dp[-1][3]
print(solve())


n = int(input())
s = input()
ans = 0
mod = int(1000000000.0 + 7)
cnt_a = 0
cnt_c = 0
ver_a = 1
ver_c = 1
for c in reversed(s):
	if c == 'c':
		cnt_c += ver_c
	if c == '?':
		cnt_c = (cnt_c * 3 + ver_c) % mod
		ver_c = ver_c * 3 % mod
for c in s:
	if c == 'c':
		cnt_c = (cnt_c - ver_c + mod) % mod
	if c == 'b':
		ans = (ans + cnt_a * cnt_c) % mod
	if c == 'a':
		cnt_a = (cnt_a + ver_a) % mod
	if c == '?':
		if ver_c % 3 == 1:
			ver_c += mod
		elif ver_c % 3 == 2:
			ver_c += mod * 2
		ver_c = ver_c // 3 % mod
		cnt_c = (cnt_c - ver_c + mod) % mod
		if cnt_c % 3 == 1:
			cnt_c += mod
		elif cnt_c % 3 == 2:
			cnt_c += mod * 2
		cnt_c = cnt_c // 3 % mod
		ans = (ans + cnt_a * cnt_c) % mod
		cnt_a = (cnt_a * 3 + ver_a) % mod
		ver_a = ver_a * 3 % mod
print(ans)


from __future__ import division, print_function
import bisect
import math
import heapq
import itertools
import sys
from collections import deque
from atexit import register
from collections import Counter
from functools import reduce
if sys.version_info[0] < 3:
	from io import BytesIO as stream
else:
	from io import StringIO as stream
if sys.version_info[0] < 3:

	class dict(dict):

		def items(self):
			return dict.iteritems(self)

		def keys(self):
			return dict.iterkeys(self)

		def values(self):
			return dict.itervalues(self)
	input = raw_input
	range = xrange
	filter = itertools.ifilter
	map = itertools.imap
	zip = itertools.izip

def sync_with_stdio(sync=True):
	global input, flush
	if sync:
		flush = sys.stdout.flush
	else:
		sys.stdin = stream(sys.stdin.read())
		input = lambda : sys.stdin.readline().rstrip('\r\n')
		sys.stdout = stream()
		register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))

def main():
	mod = 10 ** 9
	mod += 7
	n = int(input())
	s = input()
	dp = [[0 for i in range(4)] for j in range(n + 1)]
	for i in range(n):
		dp[i][3] = 1
	for i in range(n):
		for j in range(4):
			dp[i + 1][j] = dp[i][j]
		if s[i] == '?':
			for j in range(4):
				dp[i + 1][j] = 3 * dp[i][j]
			for j in range(3):
				dp[i + 1][j] += dp[i][j - 1]
		else:
			dp[i + 1][ord(s[i]) - ord('a')] += dp[i][ord(s[i]) - ord('a') - 1]
		for j in range(4):
			dp[i + 1][j] %= mod
	print(dp[n][2])
sync_with_stdio(False)
main()


z = int(input())
s = input()
mo = 10 ** 9 + 7
(a, b, c, v) = (0, 0, 0, 1)
for i in range(z):
	if s[i] == 'a':
		a += v
	elif s[i] == 'b':
		b += a
	elif s[i] == 'c':
		c += b
	else:
		c = (3 * c + b) % mo
		b = (3 * b + a) % mo
		a = (3 * a + v) % mo
		v = 3 * v % mo
print(c % mo)


from sys import stdin, stdout
import collections, heapq, bisect, math
input = stdin.readline

def rint():
	return int(input())

def rstr():
	return input().strip()

def rlstr():
	return list(input().strip().split())

def rlint():
	return list(map(int, input().split()))

def main():
	n = rint()
	s = rstr()
	mod = 10 ** 9 + 7
	at = 1
	a = ab = abc = 0
	for i in range(n):
		if s[i] == 'a':
			a += at
		elif s[i] == 'b':
			ab += a
		elif s[i] == 'c':
			abc += ab
		elif s[i] == '?':
			abc = 3 * abc + ab
			ab = 3 * ab + a
			a = 3 * a + at
			at *= 3
		abc %= mod
		ab %= mod
		a %= mod
		at %= mod
	print(abc)
main()


from bisect import *
from collections import *
from math import *
from heapq import *
from typing import List
from itertools import *
from operator import *
from functools import *
import sys
n = int(input())
arr = input()
mod = 10 ** 9 + 7
a = b = c = 0
x = 1
for ch in arr:
	if ch == 'a':
		a = (a + x) % mod
	elif ch == 'b':
		b = (b + a) % mod
	elif ch == 'c':
		c = (c + b) % mod
	else:
		(a, b, c) = ((3 * a + x) % mod, (3 * b + a) % mod, (3 * c + b) % mod)
		x = 3 * x % mod
print(c)


n = int(input())
s = input()
mod = int(1000000000.0 + 7)
ans = [1, 0, 0, 0]
for (_, c) in enumerate(s):
	nex = []
	if c == 'c':
		ans[3] += ans[2]
	elif c == 'b':
		ans[2] += ans[1]
	elif c == 'a':
		ans[1] += ans[0]
	else:
		ans[3] = ans[3] * 3 + ans[2]
		ans[2] = ans[2] * 3 + ans[1]
		ans[1] = ans[1] * 3 + ans[0]
		ans[0] *= 3
	for i in range(4):
		ans[i] %= mod
print(ans[-1])


size = int(input())
stre = input()
k = 0
types = [0, 0, 0, 0, 0, 0, 0]
ans = [0, 0, 0, 0]
for i in stre:
	if i == 'a':
		types[0] += 1
	elif i == 'b':
		types[2] += types[0]
		types[4] += types[1]
	elif i == 'c':
		ans[0] += types[2]
		ans[1] += types[4]
		ans[1] += types[3]
		ans[2] += types[5]
	elif i == '?':
		k += 1
		ans[1] += types[2]
		ans[2] += types[4]
		ans[2] += types[3]
		ans[3] += types[5]
		types[3] += types[0]
		types[5] += types[1]
		types[1] += 1
kn3 = int(3 ** (k - 3))
kn2 = int(3 ** (k - 2))
kn1 = int(3 ** (k - 1))
kn = int(3 ** k)
mod = 10 ** 9 + 7
print((ans[0] * kn + ans[1] * kn1 + ans[2] * kn2 + ans[3] * kn3) % mod)


import sys
sys.setrecursionlimit(10 ** 5)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.buffer.readline())

def MI():
	return map(int, sys.stdin.buffer.readline().split())

def LI():
	return list(map(int, sys.stdin.buffer.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def BI():
	return sys.stdin.buffer.readline()[:-1]

def SI():
	return sys.stdin.buffer.readline()[:-1].decode()
md = 10 ** 9 + 7
n = II()
s = SI()
dp = [[0] * 4 for _ in range(3)]
q = 0
for c in s:
	if c == 'a':
		dp[0][0] += 1
	if c == 'b':
		for j in range(2):
			dp[1][j] += dp[0][j]
	if c == 'c':
		for j in range(3):
			dp[2][j] += dp[1][j]
	if c == '?':
		q += 1
		for j in range(3):
			dp[2][j + 1] += dp[1][j]
		for j in range(2):
			dp[1][j + 1] += dp[0][j]
		dp[0][1] += 1
ans = 0
for j in range(4):
	ans += dp[2][j] * pow(3, q - j, md)
	ans %= md
print(ans)


def pow3(a):
	return 0 if a == -1 else p[a]
afdsfasdf = int(input())
s = list(input())
n = len(s)
mod = pow(10, 9) + 7
x = [[0] * 2 for _ in range(n - 1)]
y = [[0] * 2 for _ in range(n - 1)]
p = [1] * n
ans = 0
for i in range(1, n):
	p[i] = 3 * p[i - 1] % mod
for i in range(n - 2):
	if s[i] == 'a':
		x[i + 1][0] = 1
	elif s[i] == '?':
		x[i + 1][1] = 1
	for j in range(2):
		x[i + 1][j] += x[i][j]
	k = n - i - 1
	if s[k] == 'c':
		y[i + 1][0] = 1
	elif s[k] == '?':
		y[i + 1][1] = 1
	for j in range(2):
		y[i + 1][j] += y[i][j]
for i in range(n - 2):
	(j, k) = (i + 1, n - i - 2)
	if s[j] == 'b' or s[j] == '?':
		c1 = (x[j][0] * pow3(x[j][1]) + x[j][1] * pow3(x[j][1] - 1)) % mod
		c2 = (y[k][0] * pow3(y[k][1]) + y[k][1] * pow3(y[k][1] - 1)) % mod
		ans += c1 * c2
		ans %= mod
print(ans)


import io
import os
from collections import Counter, defaultdict, deque

def solve(N, S):
	MOD = 10 ** 9 + 7
	k = 0
	dp = [[0 for i in range(N + 1)] for j in range(3)]
	for i in range(N):
		c = S[i]
		if c == '?':
			dp[0][i] = (3 * dp[0][i - 1] + pow(3, k, MOD)) % MOD
			dp[1][i] = (3 * dp[1][i - 1] + dp[0][i - 1]) % MOD
			dp[2][i] = (3 * dp[2][i - 1] + dp[1][i - 1]) % MOD
		else:
			dp[0][i] = (dp[0][i - 1] + (pow(3, k, MOD) if c == 'a' else 0)) % MOD
			dp[1][i] = (dp[1][i - 1] + (dp[0][i - 1] if S[i] == 'b' else 0)) % MOD
			dp[2][i] = (dp[2][i - 1] + (dp[1][i - 1] if S[i] == 'c' else 0)) % MOD
		k += int(c == '?')
	if False:
		print('', '  '.join(S))
		print(dp[0])
		print(dp[1])
		print(dp[2])
	return dp[2][N - 1] % MOD
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(N,) = [int(x) for x in input().split()]
S = input().decode().rstrip()
ans = solve(N, S)
print(ans)


n = int(input())
s = input()
mod = 1000000000.0 + 7
d = [[0] * 4 for i in range(n + 1)]
d[0][0] = 1
for i in range(n):
	for j in range(4):
		if s[i] == '?':
			d[i + 1][j] = d[i][j] * 3
		else:
			d[i + 1][j] = d[i][j]
	if s[i] == 'a' or s[i] == '?':
		d[i + 1][1] += d[i][0]
	if s[i] == 'b' or s[i] == '?':
		d[i + 1][2] += d[i][1]
	if s[i] == 'c' or s[i] == '?':
		d[i + 1][3] += d[i][2]
	for j in range(4):
		d[i + 1][j] %= mod
print(int(d[-1][-1]))


import sys
import math
input = sys.stdin.readline
n = int(input())
arr = input().rstrip()
m = 10 ** 9 + 7
ca = 0
cab = 0
cabc = 0
s_count = 1
for i in range(n):
	if arr[i] == 'a':
		ca += s_count
	elif arr[i] == 'b':
		cab += ca
	elif arr[i] == 'c':
		cabc += cab
	else:
		cabc = 3 * cabc + cab
		cab = 3 * cab + ca
		ca = 3 * ca + s_count
		s_count = s_count * 3 % m
	ca = ca % m
	cab = cab % m
	cabc = cabc % m
print(cabc % m)


n = int(input())
s = input().lower()
dp_a = 0
dp_ab = 0
dp_abc = 0
hatena = 1
mod = 10 ** 9 + 7
for i in range(n):
	if s[i] == 'a':
		dp_a = (dp_a + hatena) % mod
	elif s[i] == 'b':
		dp_ab = (dp_a + dp_ab) % mod
	elif s[i] == 'c':
		dp_abc = (dp_ab + dp_abc) % mod
	else:
		dp_abc = (dp_ab + 3 * dp_abc) % mod
		dp_ab = (3 * dp_ab + dp_a) % mod
		dp_a = (3 * dp_a + hatena) % mod
		hatena = hatena * 3 % mod
print(dp_abc)


n = int(input())
s = input()
d1 = 0
d2 = 0
d3 = 0
counter = 1
m = pow(10, 9) + 7
for i in range(n):
	if s[i] == 'a':
		d1 = (d1 + counter) % m
	elif s[i] == 'b':
		d2 = (d2 + d1) % m
	elif s[i] == 'c':
		d3 = (d3 + d2) % m
	else:
		d3 = (d3 * 3 + d2) % m
		d2 = (d2 * 3 + d1) % m
		d1 = (d1 * 3 + counter) % m
		counter = counter * 3 % m
print(d3 % m)


import bisect
import array
import functools
import math
mo = 1000000007
n = int(input())
a = array.array('i', [0 for i in range(4)])
s = input()
a[0] = 1
for i in range(n):
	b = array.array('i', [0 for i in range(4)])
	key = 1
	if s[i] == '?':
		key = 3
	for j in range(4):
		b[j] = a[j] * key % mo
	if s[i] == '?' or s[i] == 'a':
		b[1] = (b[1] + a[0]) % mo
	if s[i] == '?' or s[i] == 'b':
		b[2] = (b[2] + a[1]) % mo
	if s[i] == '?' or s[i] == 'c':
		b[3] = (b[3] + a[2]) % mo
	a = b
print(a[3])


n = int(input())
if n < 3:
	print(0)
else:
	a = 0
	ab = 0
	abc = 0
	count = 1
	modv = 10 ** 9 + 7
	for i in input():
		if i == 'a':
			a += count
		elif i == 'b':
			ab += a
		elif i == 'c':
			abc += ab
		else:
			abc = (abc * 3 + ab) % modv
			ab = (ab * 3 + a) % modv
			a = (a * 3 + count) % modv
			count = 3 * count % modv
	print(abc % modv)


import sys, math
import io, os
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter

def data():
	return sys.stdin.readline().strip()

def mdata():
	return list(map(int, data().split()))

def outl(var):
	sys.stdout.write('\n'.join(map(str, var)) + '\n')

def out(var):
	sys.stdout.write(str(var) + '\n')
from decimal import Decimal
mod = 10 ** 9 + 7
INF = float('inf')
n = int(data())
s = data()
a = 0
ab = 0
abc = 0
t = 1
for i in s:
	if i == 'a':
		a = a + t
	elif i == 'b':
		ab = ab + a
	elif i == 'c':
		abc = abc + ab
	else:
		abc = 3 * abc + ab
		ab = 3 * ab + a
		a = 3 * a + t
		t = t * 3 % mod
	a = a % mod
	ab = ab % mod
	abc = abc % mod
out(abc)


mod = 10 ** 9 + 7
n = int(input())
s = input()
cc = 0
cbc = 0
res = 0
x = 1
for i in range(n - 1, -1, -1):
	if s[i] == 'c':
		cc = (cc + x) % mod
	elif s[i] == 'b':
		cbc = (cbc + cc) % mod
	elif s[i] == 'a':
		res = (res + cbc) % mod
	else:
		res = (res * 3 + cbc) % mod
		cbc = (3 * cbc + cc) % mod
		cc = (3 * cc + x) % mod
		x = x * 3 % mod
print(res)


from sys import stdin
from collections import defaultdict
MOD = 10 ** 9 + 7

def solve():
	n = int(input())
	s = input()
	dp = [0, 0, 0]
	m = 1
	for c in s:
		if c == 'a':
			dp[0] += m
		elif c == 'b':
			dp[1] += dp[0]
		elif c == 'c':
			dp[2] += dp[1]
		else:
			(dp[0], dp[1], dp[2]) = (dp[0] * 3 + m, dp[1] * 3 + dp[0], dp[2] * 3 + dp[1])
			m *= 3
		dp[0] %= MOD
		dp[1] %= MOD
		dp[2] %= MOD
		m %= MOD
	print(dp[2])
solve()


import sys

def input():
	return sys.stdin.readline().strip()

def list2d(a, b, c):
	return [[c for j in range(b)] for i in range(a)]

def list3d(a, b, c, d):
	return [[[d for k in range(c)] for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e for l in range(d)] for k in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 19
MOD = 10 ** 9 + 7
EPS = 10 ** (-10)
N = INT()
S = input()
dp0 = [0] * (N + 1)
dp1 = [0] * (N + 1)
dp2 = [0] * (N + 1)
dp3 = [0] * (N + 1)
dp0[0] = 1
for i in range(N):
	if S[i] == 'a':
		dp0[i + 1] += dp0[i]
		dp1[i + 1] += dp1[i]
		dp2[i + 1] += dp2[i]
		dp3[i + 1] += dp3[i]
		dp1[i + 1] += dp0[i]
	elif S[i] == 'b':
		dp0[i + 1] += dp0[i]
		dp1[i + 1] += dp1[i]
		dp2[i + 1] += dp2[i]
		dp3[i + 1] += dp3[i]
		dp2[i + 1] += dp1[i]
	elif S[i] == 'c':
		dp0[i + 1] += dp0[i]
		dp1[i + 1] += dp1[i]
		dp2[i + 1] += dp2[i]
		dp3[i + 1] += dp3[i]
		dp3[i + 1] += dp2[i]
	else:
		dp0[i + 1] += dp0[i] * 3
		dp1[i + 1] += dp1[i] * 3
		dp2[i + 1] += dp2[i] * 3
		dp3[i + 1] += dp3[i] * 3
		dp1[i + 1] += dp0[i]
		dp2[i + 1] += dp1[i]
		dp3[i + 1] += dp2[i]
	dp0[i + 1] %= MOD
	dp1[i + 1] %= MOD
	dp2[i + 1] %= MOD
	dp3[i + 1] %= MOD
ans = dp3[N]
print(ans)


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush, nsmallest
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
from decimal import Decimal
mod = pow(10, 9) + 7
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(var):
	sys.stdout.write(str(var) + '\n')

def outa(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
n = int(data())
s = data()
(a, b, c) = (0, 0, 0)
temp = 1
for i in s:
	if i == 'a':
		a = (a + temp) % mod
		continue
	if i == 'b':
		b = (b + a) % mod
		continue
	if i == 'c':
		c = (c + b) % mod
		continue
	c = (c * 3 + b) % mod
	b = (b * 3 + a) % mod
	a = (a * 3 + temp) % mod
	temp = temp * 3 % mod
out(c)


mod = int(1000000000.0 + 7)
(n, s) = (int(input()), input())
seen = {'a': 0, 'ab': 0, 'abc': 0, '': 1}
for c in s:
	if c == 'a':
		seen['a'] = (seen['a'] + seen['']) % mod
	elif c == 'b':
		seen['ab'] = (seen['ab'] + seen['a']) % mod
	elif c == 'c':
		seen['abc'] = (seen['abc'] + seen['ab']) % mod
	else:
		seen['abc'] = (seen['ab'] + 3 * seen['abc']) % mod
		seen['ab'] = (seen['a'] + 3 * seen['ab']) % mod
		seen['a'] = (seen[''] + 3 * seen['a']) % mod
		seen[''] = seen[''] * 3 % mod
print(seen['abc'])


n = int(input())
s = input()
a = [[0, 0, 0] for i in range(4)]
k = s.count('?')
b = [1]
for i in range(k):
	b.append(b[i] * 3 % 1000000007)
for i in range(n):
	if s[i] == 'a':
		a[0][0] += 1
	elif s[i] == 'b':
		a[0][1] += a[0][0]
		a[1][1] += a[1][0]
	elif s[i] == 'c':
		a[0][2] += a[0][1]
		a[1][2] += a[1][1]
		a[2][2] += a[2][1]
	else:
		a[3][2] += a[2][1]
		a[2][2] += a[1][1]
		a[2][1] += a[1][0]
		a[1][2] += a[0][1]
		a[1][1] += a[0][0]
		a[1][0] += 1
z = 0
for i in range(min(k + 1, 4)):
	z += a[i][2] * b[k - i]
print(z % 1000000007)


def main():
	n = int(input())
	s = input()
	(a, b, ans) = (0, 0, 0)
	cnt = 1
	for i in range(n):
		if s[i] == '?':
			ans = (ans * 3 + b) % 1000000007
			b = (b * 3 + a) % 1000000007
			a = (a * 3 + cnt) % 1000000007
			cnt = cnt * 3 % 1000000007
		elif s[i] == 'c':
			ans = (ans + b) % 1000000007
		elif s[i] == 'b':
			b = (b + a) % 1000000007
		elif s[i] == 'a':
			a = (a + cnt) % 1000000007
	print(ans)
tn = 1
for _ in range(tn):
	main()


from sys import stdout, stdin, setrecursionlimit
from bisect import insort, bisect, bisect_right
from io import BytesIO, IOBase
from collections import *
from itertools import *
from random import *
from string import *
from queue import *
from heapq import *
from math import *
from re import *
from os import *

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = read(self._fd, max(fstat(self._fd).st_size, 8192))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = read(self._fd, max(fstat(self._fd).st_size, 8192))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(stdin, stdout) = (IOWrapper(stdin), IOWrapper(stdout))
(graph, mod, szzz) = ({}, 10 ** 9 + 7, lambda : sorted(zzz()))

def getStr():
	return input()

def getInt():
	return int(input())

def listStr():
	return list(input())

def getStrs():
	return input().split()

def isInt(s):
	return '0' <= s[0] <= '9'

def input():
	return stdin.readline().strip()

def zzz():
	return [int(i) for i in input().split()]

def output(answer, end='\n'):
	stdout.write(str(answer) + end)

def lcd(xnum1, xnum2):
	return xnum1 * xnum2 // gcd(xnum1, xnum2)
dx = [-1, 1, 0, 0, 1, -1, 1, -1]
dy = [0, 0, 1, -1, 1, -1, -1, 1]
daysInMounth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
n = getInt()
arr = getStr()
ca = cab = cabc = 0
cs = 1
for i in arr:
	if i == 'a':
		ca += cs
		ca %= mod
	elif i == 'b':
		cab += ca
		cab %= mod
	elif i == 'c':
		cabc += cab
		cabc %= mod
	else:
		cabc = (3 * cabc + cab) % mod
		cab = (3 * cab + ca) % mod
		ca = (3 * ca + cs) % mod
		cs = 3 * cs % mod
print(cabc)


import sys, math
from collections import Counter, deque, defaultdict
from bisect import bisect_left, bisect_right
mod = 10 ** 9 + 7
INF = float('inf')

def inp():
	return int(sys.stdin.readline())

def inpl():
	return list(map(int, sys.stdin.readline().split()))
n = inp()
s = sys.stdin.readline()
s = s[:n]
dp = [[0] * 4 for _ in range(n + 1)]
dp[0][0] = 1
for (i, x) in enumerate(s):
	for j in range(4):
		if x == '?':
			dp[i + 1][j] = dp[i][j] * 3
		else:
			dp[i + 1][j] = dp[i][j]
	if x == 'a' or x == '?':
		dp[i + 1][1] += dp[i][0]
	if x == 'b' or x == '?':
		dp[i + 1][2] += dp[i][1]
	if x == 'c' or x == '?':
		dp[i + 1][3] += dp[i][2]
	for j in range(4):
		dp[i + 1][j] %= mod
print(dp[-1][-1])


n = int(input())
S = list(input())
mod = 10 ** 9 + 7
dpa = [0] * (2 * 10 ** 5 + 10)
dpc = [0] * (2 * 10 ** 5 + 10)
hatena_count = 0
pow3 = [1] * (2 * 10 ** 5 + 10)
for i in range(1, 2 * 10 ** 5 + 10):
	pow3[i] = pow3[i - 1] * 3 % mod
for i in range(n):
	if S[i] == 'a':
		dpa[i + 1] = (dpa[i] + pow3[hatena_count]) % mod
	elif S[i] == '?':
		dpa[i + 1] = (3 * dpa[i] + pow3[hatena_count]) % mod
		hatena_count += 1
	else:
		dpa[i + 1] = dpa[i]
S.reverse()
hatena_count = 0
for i in range(n):
	if S[i] == 'c':
		dpc[i + 1] = (dpc[i] + pow3[hatena_count]) % mod
	elif S[i] == '?':
		dpc[i + 1] = (3 * dpc[i] + pow3[hatena_count]) % mod
		hatena_count += 1
	else:
		dpc[i + 1] = dpc[i]
ans = 0
for i in range(1, n - 1):
	if S[i] == 'b' or S[i] == '?':
		ans += dpa[n - 1 - i] * dpc[i]
		ans %= mod
print(ans)


n = int(input())
s = '-'
s += input()
a = 0
b = 0
c = 0
m = 1
mod = 10 ** 9 + 7
l = len(s)
for i in range(1, l):
	if s[i] == 'a':
		a = (a + m) % mod
	elif s[i] == 'b':
		b = (b + a) % mod
	elif s[i] == 'c':
		c = (c + b) % mod
	elif s[i] == '?':
		c = (c * 3 + b) % mod
		b = (b * 3 + a) % mod
		a = (a * 3 + m) % mod
		m = m * 3 % mod
print(c)


class CodeforcesTask1426FSolution:

	def __init__(self):
		self.result = '24'

	def read_input(self):
		self.n = input()
		self.seq = input()

	def process_task(self):
		M = 10 ** 9 + 7
		o = a = b = 0
		v = 1
		for c in self.seq:
			if c == 'a':
				a += v
			elif c == 'b':
				b += a
			elif c == 'c':
				o += b
			else:
				(a, b, o, v) = ((3 * a + v) % M, (3 * b + a) % M, (3 * o + b) % M, 3 * v % M)
		self.result = o % M

	def get_result(self):
		return str(self.result)
Solution = CodeforcesTask1426FSolution()
Solution.read_input()
Solution.process_task()
print(Solution.get_result())


import re
import sys
MOD = 1000000007
n = input()
s = input()
num_a = 0
num_ab = 0
num_abc = 0
num_sets = 1
for char in s:
	if char == 'a':
		num_a = (num_a + num_sets + MOD) % MOD
	elif char == 'b':
		num_ab = (num_a + num_ab + MOD) % MOD
	elif char == 'c':
		num_abc = (num_ab + num_abc + MOD) % MOD
	elif char == '?':
		num_abc = (num_ab + 3 * num_abc + MOD) % MOD
		num_ab = (num_a + 3 * num_ab + MOD) % MOD
		num_a = (num_sets + 3 * num_a + MOD) % MOD
		num_sets = (3 * num_sets + MOD) % MOD
print(num_abc)


MOD = 10 ** 9 + 7

def main():
	N = int(input())
	S = input()
	pre_hatena = S[:1].count('?')
	a = S[:1].count('a')
	post_hatena = S[2:].count('?')
	c = S[2:].count('c')
	rev_3 = pow(3, MOD - 2, MOD)
	ans = 0
	for i in range(1, N - 1):
		if S[i] == '?' or S[i] == 'b':
			pre_pow = pow(3, pre_hatena, MOD)
			pre = pre_pow * a + pre_pow * rev_3 % MOD * pre_hatena
			post_pow = pow(3, post_hatena, MOD)
			post = post_pow * c + post_pow * rev_3 % MOD * post_hatena
			ans += pre * post
			ans %= MOD
		if S[i] == '?':
			pre_hatena += 1
		if S[i] == 'a':
			a += 1
		if S[i + 1] == '?':
			post_hatena -= 1
		if S[i + 1] == 'c':
			c -= 1
	print(ans)
main()


a = int(input())
s = input()
n = len(s)
pri = pow(10, 9) + 7
dp = [[[0, 0, 0] for i in range(3)] for i in range(len(s))]
ans = [1]
for i in range(a + 1):
	ans.append(ans[-1] * 3 % pri)
cnt = 0
for i in range(len(s)):
	if s[i] == 'a':
		if i == 0:
			dp[i][0][0] += 1
		else:
			dp[i][0][0] = (dp[i - 1][0][0] + dp[i - 1][1][0] + dp[i - 1][2][0] + ans[cnt]) % pri
			dp[i][0][1] = (dp[i - 1][0][1] + dp[i - 1][1][1] + dp[i - 1][2][1]) % pri
			dp[i][0][2] = (dp[i - 1][0][2] + dp[i - 1][1][2] + dp[i - 1][2][2]) % pri
	elif s[i] == 'b':
		if i != 0:
			dp[i][1][0] = (dp[i - 1][0][0] + dp[i - 1][1][0] + dp[i - 1][2][0]) % pri
			dp[i][1][2] = (dp[i - 1][0][2] + dp[i - 1][1][2] + dp[i - 1][2][2]) % pri
			dp[i][1][1] = (dp[i][1][0] + (dp[i - 1][0][1] + dp[i - 1][1][1] + dp[i - 1][2][1])) % pri
	elif s[i] == 'c':
		if i != 0:
			dp[i][2][0] = (dp[i - 1][0][0] + dp[i - 1][1][0] + dp[i - 1][2][0]) % pri
			dp[i][2][1] = (dp[i - 1][0][1] + dp[i - 1][1][1] + dp[i - 1][2][1]) % pri
			dp[i][2][2] = (dp[i][2][1] + (dp[i - 1][0][2] + dp[i - 1][1][2] + dp[i - 1][2][2])) % pri
	else:
		cnt += 1
		if i == 0:
			dp[0][0][0] += 1
			continue
		dp[i][0][0] = (dp[i - 1][0][0] + dp[i - 1][1][0] + dp[i - 1][2][0] + ans[cnt - 1]) % pri
		dp[i][0][1] = (dp[i - 1][0][1] + dp[i - 1][1][1] + dp[i - 1][2][1]) % pri
		dp[i][0][2] = (dp[i - 1][0][2] + dp[i - 1][1][2] + dp[i - 1][2][2]) % pri
		dp[i][1][0] = (dp[i - 1][0][0] + dp[i - 1][1][0] + dp[i - 1][2][0]) % pri
		dp[i][1][2] = (dp[i - 1][0][2] + dp[i - 1][1][2] + dp[i - 1][2][2]) % pri
		dp[i][1][1] = (dp[i][1][0] + (dp[i - 1][0][1] + dp[i - 1][1][1] + dp[i - 1][2][1]) % pri) % pri
		dp[i][2][0] = (dp[i - 1][0][0] + dp[i - 1][1][0] + dp[i - 1][2][0]) % pri
		dp[i][2][1] = (dp[i - 1][0][1] + dp[i - 1][1][1] + dp[i - 1][2][1]) % pri
		dp[i][2][2] = (dp[i][2][1] + (dp[i - 1][0][2] + dp[i - 1][1][2] + dp[i - 1][2][2]) % pri) % pri
print((dp[n - 1][0][2] + dp[n - 1][1][2] + dp[n - 1][2][2]) % pri)


import copy

def main():
	n = int(input())
	MOD = pow(10, 9) + 7
	s = str(input())
	dp = [[0] * 4 for _ in range(3)]
	base = 1
	for i in range(n):
		if s[i] != '?':
			p = copy.deepcopy(dp)
			(p, dp) = (dp, p)
			if s[i] == 'a':
				dp[0][0] += base
			if s[i] == 'b':
				dp[1][0] += p[0][0]
				dp[1][0] %= MOD
				dp[1][1] += p[0][1]
				dp[1][1] %= MOD
			if s[i] == 'c':
				dp[2][0] += p[1][0]
				dp[2][0] %= MOD
				dp[2][1] += p[1][1]
				dp[2][1] %= MOD
				dp[2][2] += p[1][2]
				dp[2][2] %= MOD
		else:
			p = [[0] * 4 for _ in range(3)]
			(p, dp) = (dp, p)
			for j in range(3):
				for k in range(4):
					dp[j][k] = p[j][k] * 3 % MOD
			dp[0][1] += base
			dp[1][1] += p[0][0]
			dp[1][1] %= MOD
			dp[1][2] += p[0][1]
			dp[1][2] %= MOD
			dp[2][1] += p[1][0]
			dp[2][1] %= MOD
			dp[2][2] += p[1][1]
			dp[2][2] %= MOD
			dp[2][3] += p[1][2]
			dp[2][3] %= MOD
			base *= 3
			base %= MOD
	print(sum(dp[2]) % MOD)
main()


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, random, time
inf = 10 ** 20
mod = 10 ** 9 + 7

def LI():
	return list(map(int, input().split()))

def II():
	return int(input())

def LS():
	return list(input().split())

def S():
	return input()
n = II()
s = S()
pow_calc = [1 for _ in range(n + 1)]
for i in range(1, n + 1):
	pow_calc[i] = pow_calc[i - 1] * 3
	pow_calc[i] %= mod

def solve():
	la = lq = rc = rq = 0
	ans = 0
	for char in s:
		if char == 'c':
			rc += 1
		if char == '?':
			rq += 1
	for char in s:
		if char == 'c':
			rc -= 1
		if char == '?':
			rq -= 1
		if char in {'?', 'b'}:
			l = la * pow_calc[lq] % mod + lq * pow_calc[lq - 1] % mod
			l %= mod
			r = rc * pow_calc[rq] % mod + rq * pow_calc[rq - 1] % mod
			r %= mod
			ans += l * r % mod
			ans %= mod
		if char == 'a':
			la += 1
		if char == '?':
			lq += 1
	return ans

def main():
	ans = solve()
	print(ans)
	return 0
main()


from sys import stdin
tt = 1
for loop in range(tt):
	n = int(stdin.readline())
	s = stdin.readline()[:-1]
	mod = 10 ** 9 + 7
	emp = 1
	a = 0
	ab = 0
	abc = 0
	for i in s:
		if i == 'a':
			a += emp
			a %= mod
		elif i == 'b':
			ab += a
			ab %= mod
		elif i == 'c':
			abc += ab
			abc %= mod
		else:
			newemp = emp * 3
			newa = a * 3
			newab = ab * 3
			newabc = abc * 3
			newa += emp
			newab += a
			newabc += ab
			emp = newemp % mod
			a = newa % mod
			ab = newab % mod
			abc = newabc % mod
	print(abc % mod)


import os
import sys
from io import BytesIO, IOBase
import threading
from bisect import bisect_right
from math import gcd, log
from collections import defaultdict
from pprint import pprint
from math import ceil
MOD = 10 ** 9 + 7

def binary_exp(a, b, MOD):
	if b < 0:
		return 0
	ans = 1
	while b:
		if b & 1:
			ans *= a
			ans %= MOD
		a *= a
		a %= MOD
		b //= 2
	return ans

def main():
	n = int(input())
	s = input()
	k = s.count('?')
	ans = 0
	na = 0
	nab = 0
	naq = 0
	nabq = 0
	nabqq = 0
	for i in range(n):
		if s[i] == 'a':
			na += 1
		if s[i] == 'b':
			nab += na
			nabq += naq
		if s[i] == 'c':
			ans = ans + nab * binary_exp(3, k, MOD)
			ans = ans + nabq * binary_exp(3, k - 1, MOD)
			ans = ans + nabqq * binary_exp(3, k - 2, MOD)
		if s[i] == '?':
			ans = ans + nab * binary_exp(3, k - 1, MOD)
			ans = ans + nabq * binary_exp(3, k - 2, MOD)
			ans = ans + nabqq * binary_exp(3, k - 3, MOD)
			nabqq += naq
			nabq += na
			naq += 1
		ans %= MOD
	print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(1):
	main()


import sys
import math
input = sys.stdin.readline

def inInt():
	return int(input())

def inStr():
	return input().rstrip()
a = 0
ab = 0
abc = 0
q = 0
m = int(1000000000.0 + 7)
n = inInt()
s = inStr()
for i in range(n):
	if s[i] == 'a':
		a += pow(3, q, m)
	elif s[i] == 'b':
		ab += a
	elif s[i] == 'c':
		abc += ab
	else:
		abc *= 3
		abc += ab
		ab *= 3
		ab += a
		a *= 3
		a += pow(3, q, m)
		q += 1
	a %= m
	ab %= m
	abc %= m
print(abc)


mod = 10 ** 9 + 7
n = int(input())
s = input()
s = ' ' + s
p3 = [1 for x in range(n + 1)]
for i in range(1, n + 1):
	p3[i] = p3[i - 1] * 3
	p3[i] %= mod
q = [0 for x in range(n + 1)]
for i in range(1, n + 1):
	if s[i - 1] == '?':
		q[i] = q[i - 1] + 1
	else:
		q[i] = q[i - 1]
prefix_a = [0 for x in range(n + 1)]
for i in range(1, n + 1):
	if s[i] == 'a':
		prefix_a[i] = prefix_a[i - 1] + p3[q[i]]
	elif s[i] == '?':
		prefix_a[i] = 3 * prefix_a[i - 1] + p3[q[i]]
	else:
		prefix_a[i] = prefix_a[i - 1]
	prefix_a[i] %= mod
q = [0 for x in range(n + 1)]
for i in reversed(range(1, n + 1)):
	if s[i] == '?':
		q[i - 1] = q[i] + 1
	else:
		q[i - 1] = q[i]
sufix_c = [0 for x in range(n + 2)]
for i in reversed(range(1, n + 1)):
	if s[i] == 'c':
		sufix_c[i] = sufix_c[i + 1] + p3[q[i]]
	elif s[i] == '?':
		sufix_c[i] = 3 * sufix_c[i + 1] + p3[q[i]]
	else:
		sufix_c[i] = sufix_c[i + 1]
	sufix_c[i] %= mod
ans = 0
for i in range(1, n + 1):
	if s[i] == 'b' or s[i] == '?':
		ans += prefix_a[i - 1] * sufix_c[i + 1]
		ans %= mod
print(ans)


from bisect import bisect_left, bisect_right

class Result:

	def __init__(self, index, value):
		self.index = index
		self.value = value

class BinarySearch:

	def __init__(self):
		pass

	@staticmethod
	def greater_than(num: int, func, size: int=1):
		if isinstance(func, list):
			index = bisect_right(func, num)
			if index == len(func):
				return Result(None, None)
			else:
				return Result(index, func[index])
		else:
			(alpha, omega) = (0, size - 1)
			if func(omega) <= num:
				return Result(None, None)
			while alpha < omega:
				if func(alpha) > num:
					return Result(alpha, func(alpha))
				if omega == alpha + 1:
					return Result(omega, func(omega))
				mid = (alpha + omega) // 2
				if func(mid) > num:
					omega = mid
				else:
					alpha = mid

	@staticmethod
	def less_than(num: int, func, size: int=1):
		if isinstance(func, list):
			index = bisect_left(func, num) - 1
			if index == -1:
				return Result(None, None)
			else:
				return Result(index, func[index])
		else:
			(alpha, omega) = (0, size - 1)
			if func(alpha) >= num:
				return Result(None, None)
			while alpha < omega:
				if func(omega) < num:
					return Result(omega, func(omega))
				if omega == alpha + 1:
					return Result(alpha, func(alpha))
				mid = (alpha + omega) // 2
				if func(mid) < num:
					alpha = mid
				else:
					omega = mid
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import gcd, ceil

def pre(s):
	n = len(s)
	pi = [0] * n
	for i in range(1, n):
		j = pi[i - 1]
		while j and s[i] != s[j]:
			j = pi[j - 1]
		if s[i] == s[j]:
			j += 1
		pi[i] = j
	return pi

def prod(a):
	ans = 1
	for each in a:
		ans = ans * each
	return ans

def lcm(a, b):
	return a * b // gcd(a, b)

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y
bs = BinarySearch()
for _ in range(int(input()) if not True else 1):
	n = int(input())
	s = input()
	mod = 10 ** 9 + 7
	a = []
	b = []
	c = []
	q = []
	ans = 0
	for i in range(n):
		if s[i] == 'a':
			a += [i]
		elif s[i] == 'b':
			b += [i]
		elif s[i] == 'c':
			c += [i]
		else:
			q += [i]
	q0 = pow(3, len(q), mod)
	q1 = pow(3, len(q) - 1, mod) if len(q) > 0 else 0
	q2 = pow(3, len(q) - 2, mod) if len(q) > 1 else 0
	q3 = pow(3, len(q) - 3, mod) if len(q) > 2 else 0
	(bc, bq) = ([], [])
	for i in b:
		(ind, ind2) = (bs.greater_than(i, c).index, bs.greater_than(i, q).index)
		count = 0 if ind is None else len(c) - ind
		count2 = 0 if ind2 is None else len(q) - ind2
		bc += [count]
		bq += [count2]
	for i in range(len(bc) - 2, -1, -1):
		bc[i] += bc[i + 1]
		bq[i] += bq[i + 1]
	for i in a:
		ind = bs.greater_than(i, b).index
		if ind is None:
			continue
		if bc[ind]:
			ans += bc[ind] * q0
			ans = ans % mod
		if bq[ind]:
			ans += bq[ind] * q1
			ans = ans % mod
	for i in q:
		ind = bs.greater_than(i, b).index
		if ind is None:
			continue
		if bc[ind]:
			ans += bc[ind] * q1
			ans = ans % mod
		if bq[ind]:
			ans += bq[ind] * q2
			ans = ans % mod
	(bc, bq) = ([], [])
	for i in q:
		(ind, ind2) = (bs.greater_than(i, c).index, bs.greater_than(i, q).index)
		count = 0 if ind is None else len(c) - ind
		count2 = 0 if ind2 is None else len(q) - ind2
		bc += [count]
		bq += [count2]
	for i in range(len(bc) - 2, -1, -1):
		bc[i] += bc[i + 1]
		bq[i] += bq[i + 1]
	for i in a:
		ind = bs.greater_than(i, q).index
		if ind is None:
			continue
		if bc[ind]:
			ans += bc[ind] * q1
			ans = ans % mod
		if bq[ind]:
			ans += bq[ind] * q2
			ans = ans % mod
	for i in q:
		ind = bs.greater_than(i, q).index
		if ind is None:
			continue
		if bc[ind]:
			ans += bc[ind] * q2
			ans = ans % mod
		if bq[ind]:
			ans += bq[ind] * q3
			ans = ans % mod
	print(ans)


def solve():
	n = int(input())
	s = input()
	none = 1
	a = 0
	ab = 0
	abc = 0
	MOD = 10 ** 9 + 7
	for i in s:
		if i == 'a':
			a += none
		elif i == 'b':
			ab += a
		elif i == 'c':
			abc += ab
		else:
			abc *= 3
			abc += ab
			ab *= 3
			ab += a
			a *= 3
			a += none
			none *= 3
		abc %= MOD
		ab %= MOD
		a %= MOD
		none %= MOD
	print(abc)
	return

def main():
	t = 1
	for _ in range(t):
		solve()
main()


n = int(input())
s = input()
a = 0
b = 0
o = 0
v = 1
M = 10 ** 9 + 7
for ch in s:
	if ch == 'a':
		a += v
	elif ch == 'b':
		b += a
	elif ch == 'c':
		o += b
	else:
		(a, b, o, v) = ((3 * a + v) % M, (3 * b + a) % M, (3 * o + b) % M, 3 * v % M)
print(o % M)


n = int(input())
s = input()
dp = [[0, 0, 0] for i in range(n)]
ct = 1
mod = 10 ** 9 + 7
for i in range(n):
	if i == 0:
		if s[i] == '?':
			ct *= 3
		if s[i] == 'a' or s[i] == '?':
			dp[i][0] += 1
	else:
		(aa, bb, cc) = dp[i - 1]
		if s[i] == 'a':
			dp[i][0] = aa + ct
			dp[i][1] = bb
			dp[i][2] = cc
		if s[i] == 'b':
			dp[i][0] = aa
			dp[i][1] = aa + bb
			dp[i][2] = cc
		if s[i] == 'c':
			dp[i][0] = aa
			dp[i][1] = bb
			dp[i][2] = bb + cc
		if s[i] == '?':
			dp[i][0] = aa * 3 + ct
			dp[i][1] = bb * 3 + aa
			dp[i][2] = cc * 3 + bb
			ct *= 3
	ct %= mod
	dp[i][0] %= mod
	dp[i][1] %= mod
	dp[i][2] %= mod
print(dp[-1][-1])


import sys as _sys
A = 'a'
B = 'b'
C = 'c'
QUESTION = '?'

def main():
	(n,) = _read_ints()
	s = _read_line()
	result = find_abc_subseqs_n_mod(s, mod=10 ** 9 + 7)
	print(result)

def _read_line():
	result = _sys.stdin.readline()
	assert result[-1] == '\n'
	return result[:-1]

def _read_ints():
	return map(int, _read_line().split())

def find_abc_subseqs_n_mod(string, mod):
	assert mod > 0
	ways_n_to_select_passed_a = _find_ways_n_to_select_passed(string, A, mod=mod)
	ways_n_to_select_unpassed_c = _find_ways_n_to_select_passed(string[::-1], C, mod=mod)[::-1]
	result = 0
	for (i_char, char) in enumerate(string):
		if i_char == 0 or i_char == len(string) - 1:
			continue
		if char == B or char == QUESTION:
			result += ways_n_to_select_passed_a[i_char - 1] * ways_n_to_select_unpassed_c[i_char + 1]
			result %= mod
	return result

def _find_ways_n_to_select_passed(string, char_to_select, mod):
	tree_powers = [1 % mod]
	for i in range(string.count(QUESTION)):
		tree_powers.append(tree_powers[-1] * 3 % mod)
	ways_n_to_select_before = []
	fixed_a_n = 0
	questions_n = 0
	ways_n_to_select_fixed_part = 0
	ways_n_to_select_question_part = 0
	for (i_char, char) in enumerate(string):
		if char == char_to_select:
			fixed_a_n += 1
			ways_n_to_select_fixed_part += tree_powers[questions_n]
		elif char == QUESTION:
			old_ways_n_to_select = ways_n_to_select_question_part
			ways_n_to_select_question_part *= 2
			ways_n_to_select_question_part += old_ways_n_to_select + tree_powers[questions_n]
			assert ways_n_to_select_fixed_part % mod == fixed_a_n * tree_powers[questions_n] % mod
			ways_n_to_select_fixed_part = fixed_a_n * tree_powers[questions_n + 1]
			questions_n += 1
		ways_n_to_select_fixed_part %= mod
		ways_n_to_select_question_part %= mod
		ways_n_to_select = (ways_n_to_select_fixed_part + ways_n_to_select_question_part) % mod
		ways_n_to_select_before.append(ways_n_to_select)
	return ways_n_to_select_before
main()


import sys
input = sys.stdin.readline
n = int(input())
S = input().strip()
mod = 10 ** 9 + 7
A = 0
AB = 0
ABC = 0
q = 0
for s in S:
	if s == 'a':
		A += pow(3, q, mod)
	elif s == 'b':
		AB += A
	elif s == 'c':
		ABC += AB
	else:
		ABC = AB + ABC * 3
		AB = A + AB * 3
		A = pow(3, q, mod) + A * 3
		q += 1
	A %= mod
	AB %= mod
	ABC %= mod
print(ABC)


n = int(input())
s = input()
MOD = 10 ** 9 + 7
numa = 0
numab = 0
ans = 0
numa1 = 0
numab1 = 0
ans1 = 0
numab2 = 0
ans2 = 0
ans3 = 0
count = 0
for i in range(n):
	if s[i] == 'a':
		numa = (numa + 1) % MOD
	elif s[i] == 'b':
		numab = (numab + numa) % MOD
		numab1 = (numab1 + numa1) % MOD
	elif s[i] == 'c':
		ans = (ans + numab) % MOD
		ans1 = (ans1 + numab1) % MOD
		ans2 = (ans2 + numab2) % MOD
	else:
		ans1 = (ans1 + numab) % MOD
		ans2 = (ans2 + numab1) % MOD
		ans3 = (ans3 + numab2) % MOD
		numab1 = (numab1 + numa) % MOD
		numab2 = (numab2 + numa1) % MOD
		numa1 = (numa1 + 1) % MOD
		count += 1
ans = ans * pow(3, count, MOD) % MOD
if count >= 3:
	ans = (ans + ans3 * pow(3, count - 3, MOD)) % MOD
if count >= 2:
	ans = (ans + ans2 * pow(3, count - 2, MOD)) % MOD
if count >= 1:
	ans = (ans + ans1 * pow(3, count - 1, MOD)) % MOD
print(ans)


import sys
input = sys.stdin.buffer.readline
n = int(input())
mod = int(1000000000.0 + 7)
s = input().strip()
na = nab = nabc = 0
base = 1
for i in s:
	if i == ord('a'):
		na = (na + base) % mod
	elif i == ord('b'):
		nab = (nab + na) % mod
	elif i == ord('c'):
		nabc = (nabc + nab) % mod
	else:
		(na, nab, nabc) = ((na * 3 + base) % mod, (3 * nab + na) % mod, (3 * nabc + nab) % mod)
		base = base * 3 % mod
print(nabc)


for _ in range(1):
	n = int(input())
	s = input()
	div = 10 ** 9 + 7
	dp = [[0 for i in range(3)] for i in range(n + 1)]
	num = 1
	for i in range(1, n + 1):
		if s[i - 1] == 'a':
			dp[i][2] = (dp[i - 1][2] + num) % div
			dp[i][1] = dp[i - 1][1] % div
			dp[i][0] = dp[i - 1][0] % div
		elif s[i - 1] == 'b':
			dp[i][2] = dp[i - 1][2] % div
			dp[i][1] = (dp[i - 1][1] + dp[i - 1][2]) % div
			dp[i][0] = dp[i - 1][0] % div
		elif s[i - 1] == 'c':
			dp[i][2] = dp[i - 1][2] % div
			dp[i][1] = dp[i - 1][1] % div
			dp[i][0] = (dp[i - 1][0] + dp[i - 1][1]) % div
		else:
			dp[i][2] = (3 * dp[i - 1][2] + num) % div
			dp[i][1] = (3 * dp[i - 1][1] + dp[i - 1][2]) % div
			dp[i][0] = (3 * dp[i - 1][0] + dp[i - 1][1]) % div
			num *= 3
			num = num % div
	print(dp[n][0] % div)


n = int(input())
seq = input()
dp = [0, 0]
ans = 0
mod = int(1000000000.0 + 7)
pat = 1
for i in seq:
	if i == 'a':
		dp[0] = (dp[0] + pat) % mod
	elif i == 'b':
		dp[1] += dp[0]
		dp[1] %= mod
	elif i == 'c':
		ans = (ans + dp[1]) % mod
	else:
		ans = (3 * ans + dp[1]) % mod
		dp[1] = (3 * dp[1] + dp[0]) % mod
		dp[0] = (3 * dp[0] + pat) % mod
		pat = 3 * pat % mod
print(ans)


mod = 10 ** 9 + 7
n = int(input())
s = input()
na = 0
nb = 0
nc = 0
rt = 1
for i in range(n):
	if s[i] == '?':
		nc = 3 * nc + nb
		nb = 3 * nb + na
		na = 3 * na + rt
		rt *= 3
	elif s[i] == 'a':
		na += rt
	elif s[i] == 'b':
		nb += na
	else:
		nc += nb
	nc %= mod
	na %= mod
	nb %= mod
	rt %= mod
print(nc % mod)


pass

def main():
	n = int(input())
	arr = list(input())
	(a, b, c, t, M) = (0, 0, 0, 1, 10 ** 9 + 7)
	for i in range(n):
		if arr[i] == 'a':
			a += t
		elif arr[i] == 'b':
			b += a
		elif arr[i] == 'c':
			c += b
		else:
			(t, a, b, c) = (3 * t % M, (3 * a + t) % M, (3 * b + a) % M, (3 * c + b) % M)
	print(c % M)
main()


def solution():
	n = int(input())
	s = input()
	dp = [0] * 3
	l = 1
	mod = 10 ** 9 + 7
	for i in range(n):
		if s[i] == 'a':
			dp[0] = (dp[0] + l) % mod
		elif s[i] == 'b':
			dp[1] = (dp[1] + dp[0]) % mod
		elif s[i] == 'c':
			dp[2] = dp[2] + dp[1] % mod
		else:
			dp[2] = (3 * dp[2] + dp[1]) % mod
			dp[1] = (3 * dp[1] + dp[0]) % mod
			dp[0] = (3 * dp[0] + l) % mod
			l = l * 3 % mod
	print(dp[2] % mod)
t = 1
for _ in range(t):
	solution()


def solve(s):
	a_count = 0
	b_count = 0
	c_count = 0
	start = 1
	MOD = 10 ** 9 + 7
	for i in range(len(s)):
		if s[i] == 'a':
			a_count += start
		elif s[i] == 'b':
			b_count += a_count
		elif s[i] == 'c':
			c_count += b_count
		else:
			(a_count, b_count, c_count, start) = ((3 * a_count + start) % MOD, (3 * b_count + a_count) % MOD, (3 * c_count + b_count) % MOD, 3 * start % MOD)
	return c_count % MOD
n = input()
tmp = input()
print(solve(tmp))


import os
from sys import stdin, stdout

class Input:

	def __init__(self):
		self.lines = stdin.readlines()
		self.idx = 0

	def line(self):
		try:
			return self.lines[self.idx].strip()
		finally:
			self.idx += 1

	def array(self, sep=' ', cast=int):
		return list(map(cast, self.line().split(sep=sep)))

	def has_next(self):
		return self.idx < len(self.lines)

def known_cases(func):
	inpt = Input()
	(cases,) = inpt.array()
	for case in range(cases):
		func(inpt)

def unknown_cases(func):
	inpt = Input()
	while inpt.has_next():
		func(inpt)

@unknown_cases
def solve(inpt):
	(n,) = inpt.array()
	s = inpt.line()
	t = 'abc'
	MOD = 1000000007
	dp = [1, 0, 0, 0]
	for mv in s:
		ndp = dp.copy()
		if mv == '?':
			ndp[0] *= 3
			for i in range(3):
				ndp[i + 1] *= 3
				ndp[i + 1] += dp[i]
		else:
			i = ord(mv) - ord('a') + 1
			ndp[i] = ndp[i] + dp[i - 1]
		dp = [x % MOD for x in ndp]
	print(dp[3])


import sys
try:
	(sys.stdin, sys.stdout) = (open('in.txt', 'r'), open('out.txt', 'w'))
except:
	pass
ii1 = lambda : int(sys.stdin.readline().strip())
is1 = lambda : sys.stdin.readline().strip()
iia = lambda : list(map(int, sys.stdin.readline().strip().split()))
isa = lambda : sys.stdin.readline().strip().split()
mod = int(1000000000.0 + 7)
from collections import *
from math import *
n = ii1()
s = is1()
a = 0
y = 0
z = 0
t = 1
for i in s:
	if i == 'a':
		a = a + t
	elif i == 'b':
		y = y + a
	elif i == 'c':
		z = z + y
	else:
		z = 3 * z + y
		y = 3 * y + a
		a = 3 * a + t
		t = t * 3 % mod
	a = a % mod
	y = y % mod
	z = z % mod
print(z)


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10 ** 8)
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=2 ** 51, func=lambda a, b: a & b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
n = int(input())
s = input()
na = 0
nb = 0
nc = 0
rt = 1
for i in range(n):
	if s[i] == '?':
		nc = 3 * nc + nb
		nb = 3 * nb + na
		na = 3 * na + rt
		rt *= 3
	elif s[i] == 'a':
		na += rt
	elif s[i] == 'b':
		nb += na
	else:
		nc += nb
	nc %= mod
	na %= mod
	nb %= mod
	rt %= mod
print(nc % mod)


n = int(input())
s = input()
dp = [[0, 0, 0] for _ in range(n)]
dp2 = [[0, 0, 0] for _ in range(n)]
prev = [0, 0, 0]
free = 0
mod = 1000000007
for i in range(n):
	if i > 0:
		dp[i] = dp[i - 1].copy()
	if s[i] == 'a':
		dp[i][0] += 1
	if s[i] == 'b':
		dp[i][1] += dp[i][0]
		if dp[i][1] >= mod:
			dp[i][1] -= mod
	if s[i] == 'c':
		dp[i][2] += dp[i][1]
		if dp[i][2] >= mod:
			dp[i][2] -= mod
	if s[i] == '?':
		free += 1
for i in reversed(range(0, n)):
	if i + 1 < n:
		dp2[i] = dp2[i + 1].copy()
	if s[i] == 'c':
		dp2[i][0] += 1
	if s[i] == 'b':
		dp2[i][1] += dp2[i][0]
		if dp2[i][1] >= mod:
			dp2[i][1] -= mod
	if s[i] == 'a':
		dp2[i][2] += dp2[i][1]
		if dp2[i][2] >= mod:
			dp2[i][2] -= mod
ans = dp[n - 1][2] * pow(3, free, mod) % mod
ans += free * (free - 1) * (free - 2) // 6 * pow(3, mod - 1 + free - 3, mod) % mod
(before, after) = (0, free)
for i in range(n):
	if s[i] == '?':
		mul = pow(3, free - 1, mod)
		ans += mul * (dp[i][0] * dp2[i][0] + dp2[i][1] + dp[i][1]) % mod
		before += 1
		after -= 1
	if s[i] == 'a':
		ans += pow(3, mod - 1 + free - 2, mod) * (after * (after - 1) // 2) % mod
	if s[i] == 'b':
		ans += pow(3, mod - 1 + free - 2, mod) * (after * before) % mod
	if s[i] == 'c':
		ans += pow(3, mod - 1 + free - 2, mod) * (before * (before - 1) // 2) % mod
	if ans >= mod:
		ans %= mod
print(ans % mod)


import sys
input = sys.stdin.readline

def count(a, b):
	m = len(a)
	n = len(b)
	lookup = [[0] * (n + 1) for i in range(m + 1)]
	for i in range(n + 1):
		lookup[0][i] = 0
	for i in range(m + 1):
		lookup[i][0] = 1
	for i in range(1, m + 1):
		for j in range(1, n + 1):
			if a[i - 1] == b[j - 1]:
				lookup[i][j] = lookup[i - 1][j - 1] + lookup[i - 1][j]
			else:
				lookup[i][j] = lookup[i - 1][j]
	return lookup[m][n]
n = int(input())
s = input()
ans = 0
z = 0
for i in s:
	if i == '?':
		z += 1
n1 = count(s, 'abc')
ans = ans + pow(3, z, 1000000007) * n1
n1 = count(s, '?bc')
if z >= 1:
	ans = ans + pow(3, z - 1, 1000000007) * n1
n1 = count(s, 'a?c')
if z >= 1:
	ans = ans + pow(3, z - 1, 1000000007) * n1
n1 = count(s, 'ab?')
if z >= 1:
	ans = ans + pow(3, z - 1, 1000000007) * n1
n1 = count(s, '??c')
if z >= 2:
	ans = ans + pow(3, z - 2, 1000000007) * n1
n1 = count(s, 'a??')
if z >= 2:
	ans = ans + pow(3, z - 2, 1000000007) * n1
n1 = count(s, '?b?')
if z >= 2:
	ans = ans + pow(3, z - 2, 1000000007) * n1
n1 = count(s, '???')
if z >= 3:
	ans = ans + pow(3, z - 3, 1000000007) * n1
print(ans % 1000000007)


n = int(input())
arr = input()
(a, ab, abc, m) = (0, 0, 0, 1)
mod = 1000000007
for i in arr:
	if i == 'a':
		a = (a + m) % mod
	elif i == 'b':
		ab = (ab + a) % mod
	elif i == 'c':
		abc = (abc + ab) % mod
	else:
		abc = (3 * abc + ab) % mod
		ab = (3 * ab + a) % mod
		a = (3 * a + m) % mod
		m = 3 * m % mod
print(abc % mod)


from collections import defaultdict as dd
mod = 10 ** 9 + 7
pw = {-1: 0, 0: 1}
for i in range(1, 200001):
	pw[i] = pw[i - 1] * 3 % mod

def solve(st, n):
	(a, c, q) = (dd(int), dd(int), dd(int))
	for (i, it) in enumerate(st):
		(a[i], c[i], q[i]) = (a[i - 1], c[i - 1], q[i - 1])
		if it == 'a':
			a[i] += 1
		elif it == 'c':
			c[i] += 1
		elif it == '?':
			q[i] += 1
	ans = 0
	for i in range(n):
		if st[i] in '?b':
			(ca, q1) = (a[i - 1], q[i - 1])
			(cc, q2) = (c[n - 1] - c[i], q[n - 1] - q[i])
			ta = ca * pw[q1] % mod
			ta = (ta + q1 * pw[q1 - 1]) % mod
			tc = cc * pw[q2] % mod
			tc = (tc + q2 * pw[q2 - 1]) % mod
			ans += ta * tc
			ans %= mod
	return ans
n = int(input())
st = input()
ans = solve(st, n)
print(ans)


mod = 10 ** 9 + 7
(N,) = list(map(int, input().split()))
s = input().strip()
a = 0
b = 0
c = 0
t = 1
for i in range(N):
	if s[i] == 'a':
		a = (a + t) % mod
	elif s[i] == 'b':
		b = (b + a) % mod
	elif s[i] == 'c':
		c = (c + b) % mod
	elif s[i] == '?':
		(t, a, b, c) = (t * 3 % mod, (a * 3 + t) % mod, (b * 3 + a) % mod, (c * 3 + b) % mod)
print(c)


MAXN = 200005
MOD = 1000000007
n = int(input())
s = input()
dp = [[0, 0, 0] for i in range(MAXN)]
q_cnt = 0
a_cnt = 0
for (i, cur) in enumerate(s):
	i += 1
	if cur == '?':
		q_cnt += 1
		dp[i][0] = a_cnt * pow(3, q_cnt, MOD) + q_cnt * pow(3, q_cnt - 1, MOD)
		dp[i][1] = dp[i - 1][1] * 3 + dp[i - 1][0]
		dp[i][2] = dp[i - 1][2] * 3 + dp[i - 1][1]
	elif cur == 'a':
		a_cnt += 1
		dp[i][0] = dp[i - 1][0] + pow(3, q_cnt, MOD)
		dp[i][1] = dp[i - 1][1]
		dp[i][2] = dp[i - 1][2]
	elif cur == 'b':
		dp[i][0] = dp[i - 1][0]
		dp[i][1] = dp[i - 1][1] + dp[i - 1][0]
		dp[i][2] = dp[i - 1][2]
	elif cur == 'c':
		dp[i][0] = dp[i - 1][0]
		dp[i][1] = dp[i - 1][1]
		dp[i][2] = dp[i - 1][2] + dp[i - 1][1]
	for j in range(3):
		dp[i][j] %= MOD
print(dp[n][2])


n = int(input())
word = input()
P = [[0, 0, 0] for _ in range(n + 1)]
P_w = [0, 0, 0]
cnt = 1
mod = int(1000000000.0 + 7)
for i in range(n):
	P[i + 1][0] = P[i][0]
	P[i + 1][1] = P[i][1]
	P[i + 1][2] = P[i][2]
	if word[i] == 'a':
		P[i + 1][0] = (P[i][0] + cnt) % mod
	elif word[i] == 'b':
		P[i + 1][1] = (P[i][1] + P[i][0]) % mod
	elif word[i] == 'c':
		P[i + 1][2] = (P[i][2] + P[i][1]) % mod
	elif word[i] == '?':
		P[i + 1][2] = (3 * P[i][2] + P[i][1]) % mod
		P[i + 1][1] = (3 * P[i][1] + P[i][0]) % mod
		P[i + 1][0] = (3 * P[i][0] + cnt) % mod
		cnt = cnt * 3 % mod
print(P[-1][2])


import sys
input = sys.stdin.readline
n = int(input())
s = list(input().rstrip())
mod = 10 ** 9 + 7
ans = 0
a = 0
b = 0
v = 1
for ss in s:
	if ss == 'a':
		a += v
	elif ss == 'b':
		b += a
	elif ss == 'c':
		ans += b
	else:
		(a, b, ans, v) = ((3 * a + v) % mod, (3 * b + a) % mod, (3 * ans + b) % mod, 3 * v % mod)
print(ans % mod)


def num(s):
	ans1 = [0] * n
	for q in range(n):
		ans1[q] = s[q] == 'a'
	sum1 = 0
	for q in range(n):
		w = sum1 * (s[q] == 'b')
		sum1 += ans1[q]
		ans1[q] = w
	sum1 = 0
	for q in range(n):
		w = sum1 * (s[q] == 'c')
		sum1 += ans1[q]
		ans1[q] = w
	sum1 = 0
	for q in range(n):
		sum1 += ans1[q]
	return sum1 % C
n = int(input())
s = list(input())
(C, k) = (10 ** 9 + 7, 0)
(ans, ans1, deg) = ([0] * n, [0] * n, [1])
for q in range(n):
	deg.append(deg[-1] * 3 % C)
	k += s[q] == '?'
if k == 0:
	print(num(s))
elif k == 1:
	ans = 0
	for q in range(n):
		if s[q] == '?':
			for q1 in ['a', 'b', 'c']:
				s[q] = q1
				ans += num(s)
			break
	print(ans % C)
elif k == 2:
	ans = 0
	ind1 = ind2 = -1
	for q in range(n):
		if s[q] == '?' and ind1 == -1:
			ind1 = q
		elif s[q] == '?':
			ind2 = q
	for q in ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']:
		(s[ind1], s[ind2]) = (q[0], q[1])
		ans += num(s)
	print(ans % C)
else:
	ans = 0
	for q1 in ['???', '??c', '?b?', '?bc', 'a??', 'a?c', 'ab?', 'abc']:
		t = q1.count('?')
		ans1 = [0] * n
		for q in range(n):
			ans1[q] = (s[q] == q1[0]) * deg[k - t]
		sum1 = 0
		for q in range(n):
			w = sum1 * (s[q] == q1[1])
			sum1 += ans1[q]
			ans1[q] = w % C
		sum1 = 0
		for q in range(n):
			w = sum1 * (s[q] == q1[2])
			sum1 += ans1[q]
			ans1[q] = w % C
		sum1 = 0
		for q in range(n):
			sum1 += ans1[q]
		ans += sum1
	print(ans % C)


import os
from sys import stdin, stdout

class Input:

	def __init__(self):
		self.it = iter(stdin.readlines())

	def line(self):
		return next(self.it).strip()

	def array(self, sep=' ', cast=int):
		return list(map(cast, self.line().split(sep=sep)))

def known_cases(func):
	inpt = Input()
	(cases,) = inpt.array()
	for case in range(cases):
		func(inpt)

def unknown_cases(func):
	inpt = Input()
	while True:
		try:
			func(inpt)
		except StopIteration:
			break

@unknown_cases
def solve(inpt):
	(n,) = inpt.array()
	s = inpt.line()
	MOD = 1000000007
	dp = [1, 0, 0, 0]
	for mv in s:
		ndp = dp.copy()
		if mv == '?':
			ndp[0] *= 3
			for i in range(3):
				ndp[i + 1] *= 3
				ndp[i + 1] += dp[i]
		else:
			i = ord(mv) - ord('a') + 1
			ndp[i] = ndp[i] + dp[i - 1]
		dp = [x % MOD for x in ndp]
	print(dp[3])


mod = 10 ** 9 + 7
p3 = [0] * 200000
p3[0] = 1
for i in range(1, len(p3)):
	p3[i] = 3 * p3[i - 1] % mod

def f(lAm, qAm):
	return (lAm * p3[lAm - 1] % mod + p3[lAm] * qAm % mod) % mod
n = int(input())
data = list(input())
aAm_ = 0
qAm_ = 0
cAm_ = 0
aAm = [0] * n
qAm = [0] * n
cAm = [0] * n
for i in range(n):
	if data[i] == 'a':
		aAm_ += 1
	elif data[i] == '?':
		qAm_ += 1
	elif data[i] == 'c':
		cAm_ += 1
	aAm[i] = aAm_
	qAm[i] = qAm_
	cAm[i] = cAm_
ans = 0
for i in range(n):
	if data[i] == 'b' or data[i] == '?':
		aBefore = aAm[i]
		qBefore = qAm[i] - (data[i] == '?')
		cAfter = cAm[-1] - cAm[i]
		qAfter = qAm[-1] - qAm[i]
		ans += f(qBefore, aBefore) * f(qAfter, cAfter) % mod
		ans %= mod
print(int(ans))


from sys import stdin, stdout, setrecursionlimit
import heapq
from math import gcd, ceil, sqrt
from collections import Counter, deque
from bisect import bisect_left, bisect_right
from itertools import combinations, permutations
ii1 = lambda : int(stdin.readline().strip())
is1 = lambda : stdin.readline().strip()
iia = lambda : list(map(int, stdin.readline().strip().split()))
isa = lambda : stdin.readline().strip().split()
setrecursionlimit(100000)
mod = 1000000007
n = ii1()
s = is1()
cnt = 1
a = ab = abc = 0
for i in s:
	if i == 'a':
		a += cnt
	elif i == 'b':
		ab += a
	elif i == 'c':
		abc += ab
	else:
		abc = 3 * abc + ab
		ab = 3 * ab + a
		a = 3 * a + cnt
		cnt *= 3
	a %= mod
	ab %= mod
	abc %= mod
	cnt %= mod
print(abc % mod)


import sys
input = sys.stdin.readline
MOD = 10 ** 9 + 7

def main():
	n = int(input())
	string = input().strip()
	dp = [[0, 0, 0, 0] for _ in range(n + 1)]
	dp[0][0] = 1
	for (i, s) in enumerate(string):
		if s == 'a':
			dp[i + 1][0] = dp[i][0]
			dp[i + 1][1] = dp[i][1] + dp[i][0]
			dp[i + 1][2] = dp[i][2]
			dp[i + 1][3] = dp[i][3]
		elif s == 'b':
			dp[i + 1][0] = dp[i][0]
			dp[i + 1][1] = dp[i][1]
			dp[i + 1][2] = dp[i][2] + dp[i][1]
			dp[i + 1][3] = dp[i][3]
		elif s == 'c':
			dp[i + 1][0] = dp[i][0]
			dp[i + 1][1] = dp[i][1]
			dp[i + 1][2] = dp[i][2]
			dp[i + 1][3] = dp[i][3] + dp[i][2]
		else:
			dp[i + 1][0] = dp[i][0] * 3
			dp[i + 1][1] = 3 * dp[i][1] + dp[i][0]
			dp[i + 1][2] = 3 * dp[i][2] + dp[i][1]
			dp[i + 1][3] = 3 * dp[i][3] + dp[i][2]
		for j in range(4):
			dp[i + 1][j] %= MOD
	print(dp[-1][-1] % MOD)
main()


MOD = 10 ** 9 + 7
n = int(input())
dp = [0] * 12
qcnt = 0
for c in input():
	new_dp = dp.copy()
	if c == 'a':
		new_dp[0] += 1
		new_dp[0] %= MOD
	elif c == 'b':
		new_dp[1] += dp[0]
		new_dp[1] %= MOD
		new_dp[4] += dp[3]
		new_dp[4] %= MOD
		new_dp[7] += dp[6]
		new_dp[7] %= MOD
		new_dp[10] += dp[9]
		new_dp[10] %= MOD
	elif c == 'c':
		new_dp[2] += dp[1]
		new_dp[2] %= MOD
		new_dp[5] += dp[4]
		new_dp[5] %= MOD
		new_dp[8] += dp[7]
		new_dp[8] %= MOD
		new_dp[11] += dp[10]
		new_dp[11] %= MOD
	else:
		qcnt += 1
		new_dp[3] += 1
		for i in range(8):
			if i % 3 == 2:
				continue
			new_dp[i + 4] += dp[i]
			new_dp[i] %= MOD
	dp = new_dp
ans = 0
for i in range(4):
	if qcnt - i < 0:
		break
	tmp = pow(3, qcnt - i, MOD)
	tmp *= dp[2 + 3 * i]
	ans += tmp % MOD
	ans %= MOD
print(ans)


for _ in range(1):
	n = int(input())
	s = input()
	suf = [0] * n
	suf[n - 1] = int(s[-1] in 'c')
	suf1 = [0] * n
	suf1[n - 1] = int(s[-1] in '?')
	mod = 10 ** 9 + 7
	m = s.count('?')
	tr0 = pow(3, m, mod)
	if m - 1 >= 0:
		tr1 = pow(3, m - 1, mod)
	else:
		tr1 = 0
	if m - 2 >= 0:
		tr2 = pow(3, m - 2, mod)
	else:
		tr2 = 0
	trob = pow(3, mod - 2, mod)
	for i in range(n - 2, -1, -1):
		suf[i] = suf[i + 1] + int(s[i] in 'c')
		suf1[i] = suf1[i + 1] + int(s[i] in '?')
	for i in range(0, n - 1):
		if s[i] not in 'b?':
			suf[i + 1] = 0
			suf1[i + 1] = 0
		if s[i] == '?':
			suf[i + 1] *= tr1
			suf1[i + 1] *= tr2
			suf[i + 1] %= mod
			suf1[i + 1] %= mod
		else:
			suf[i + 1] *= tr0
			suf[i + 1] %= mod
			suf1[i + 1] *= tr1
			suf1[i + 1] %= mod
	suf[0] = 0
	suf1[0] = 0
	ans = 0
	kek = 0
	for i in range(n - 2, -1, -1):
		if s[i] not in 'a?':
			kek += suf[i + 1]
			kek += suf1[i + 1]
			continue
		if s[i] in 'a':
			ans += kek
		else:
			lol = kek * trob % mod
			ans += lol
		kek += suf[i + 1]
		kek += suf1[i + 1]
		ans %= mod
	print(ans)


MOD = 10 ** 9 + 7
n = int(input())
s = input()
cnt = s.count('?')
(a, ab, abc) = (0, 0, 0)
(a2, ab2, abc2) = (0, 0, 0)
(a3, ab3, abc3) = (0, 0, 0)
(a4, ab4, abc4) = (0, 0, 0)
for i in s:
	if i == 'a':
		a += 1
	elif i == 'b':
		ab += a
		ab2 += a2
	elif i == 'c':
		abc += ab
		abc2 += ab2
		abc3 += ab3
	else:
		(a2, ab2, abc2, ab3, abc3, abc4) = (a2 + 1, ab2 + a, abc2 + ab, ab3 + a2, abc3 + ab2, abc4 + ab3)
if cnt == 0:
	pass
elif cnt == 1:
	abc *= 3
elif cnt == 2:
	abc *= 9
	abc2 *= 3
elif cnt == 3:
	abc *= 27
	abc2 *= 9
	abc3 *= 3
else:
	abc = abc * 3 ** cnt % MOD % MOD
	abc2 = abc2 * 3 ** (cnt - 1) % MOD % MOD
	abc3 = abc3 * 3 ** (cnt - 2) % MOD % MOD
	abc4 = abc4 * 3 ** (cnt - 3) % MOD % MOD
ans = (abc + abc2 + abc3 + abc4) % MOD
print(ans)


n = int(input())
m = 10 ** 9 + 7
s = input()
a = 0
b = 0
c = 1
ans = 0
for i in range(n):
	if s[i] == 'a':
		a += c
	elif s[i] == 'b':
		b += a
	elif s[i] == 'c':
		ans += b
		ans %= m
	else:
		ans = 3 * ans + b
		ans %= m
		b = (3 * b + a) % m
		a += c + 2 * a
		a %= m
		c *= 3
		c %= m
print(ans)


import sys
from array import array
import typing as Tp

def input():
	return sys.stdin.buffer.readline().decode('utf-8')

def main():
	n = int(input())
	s = input().rstrip()
	mod = 10 ** 9 + 7
	dp = array('i', [0, 1, 0, 0, 0])
	next_dp = array('i', [0] * 5)
	target = '*abc'
	for c in s:
		for i in range(1, 5):
			next_dp[i] = (dp[i] * (3 if c == '?' else 1) + (dp[i - 1] if c == target[i - 1] or c == '?' else 0)) % mod
		(dp, next_dp) = (next_dp, dp)
		for i in range(5):
			next_dp[i] = 0
	print(dp[-1])
main()


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(RL())

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)

def toord(c):
	return ord(c) - ord('a')

def lcm(a, b):
	return a * b // gcd(a, b)
mod = 10 ** 9 + 7
INF = float('inf')
from math import factorial, sqrt, ceil, floor, gcd
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def main():
	n = N()
	s = input()
	a = ab = abc = 0
	non = 1
	for i in range(n):
		if s[i] == 'a':
			a += non
		elif s[i] == 'b':
			ab += a
		elif s[i] == 'c':
			abc += ab
		elif s[i] == '?':
			abc = (3 * abc + ab) % mod
			ab = (3 * ab + a) % mod
			a = (3 * a + non) % mod
			non = 3 * non % mod
	print(abc % mod)
main()


MOD = 1000000007
n = int(input())
s = input()
dp = [0, 0, 0]
v = 1
for c in s:
	if c == 'a':
		dp[0] += v
	elif c == 'b':
		dp[1] += dp[0]
	elif c == 'c':
		dp[2] += dp[1]
	else:
		dp[2] = dp[2] * 3 + dp[1]
		dp[1] = dp[1] * 3 + dp[0]
		dp[0] = dp[0] * 3 + v
		v *= 3
	dp[0] %= MOD
	dp[1] %= MOD
	dp[2] %= MOD
	v %= MOD
print(dp[2])


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import ceil, floor
from copy import *
from collections import deque, defaultdict
from collections import Counter as counter
from itertools import combinations
from itertools import permutations as permutate
from bisect import bisect_left as bl
from operator import *
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192
from sys import stderr

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
from types import GeneratorType

def iterative(f, stack=[]):

	def wrapped_func(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		to = f(*args, **kwargs)
		while True:
			if type(to) is GeneratorType:
				stack.append(to)
				to = next(to)
				continue
			stack.pop()
			if not stack:
				break
			to = stack[-1].send(to)
		return to
	return wrapped_func
mod = 1000000007

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def fsep():
	return map(float, inp().split())

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def pow(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res
from functools import reduce

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))

def gcd(a, b):
	if a == b:
		return a
	while b > 0:
		(a, b) = (b, a % b)
	return a

def comb(n, r):
	if n < r:
		return 0
	else:
		return fac[n] * (finv[r] * finv[n - r] % mod) % mod

def prefix_sum(ar):
	return list(accumulate(ar))

def suffix_sum(ar):
	return list(accumulate(ar[::-1]))[::-1]

def N():
	return int(inp())
from collections import defaultdict
sys.setrecursionlimit(300000)

def numberOfSetBits(i):
	i = i - (i >> 1 & 1431655765)
	i = (i & 858993459) + (i >> 2 & 858993459)
	return ((i + (i >> 4) & 252645135) * 16843009 & 4294967295) >> 24

def solve():
	n = N()
	s = inp()
	a = 0
	b = 0
	c = 0
	t = 1
	for i in s:
		if i == 'a':
			a += t
			a %= mod
		if i == 'b':
			b += a
			b %= mod
		if i == 'c':
			c += b
			c %= mod
		if i == '?':
			c = 3 * c + b
			b = 3 * b + a
			a = 3 * a + t
			t *= 3
			a %= mod
			b %= mod
			c %= mod
			t %= mod
	print(c)
solve()


import math
teststring = '5\na???c\n'
online = __file__ != '/home/jhli/py/674/Problem_F.py'
(true, false) = (True, False)
if True:

	def spitout():
		for c in teststring.splitlines():
			yield c
	_ito = spitout()
	if not online:

		def input():
			return next(_ito)

	def build_enum(*a):
		built = dict()
		for (i, c) in enumerate(a):
			built[c] = i
		return lambda x: built[x]
n = int(input())
s = input()
l = len(s)
d0 = [1]
da = [0]
dab = [0]
dabc = [0]
M = 1000000007
for i in range(l):
	incr0 = incra = incrab = incrabc = 0
	if s[i] == 'a' or s[i] == '?':
		incr0 += d0[i]
		incra += da[i] + d0[i]
		incrab += dab[i]
		incrabc += dabc[i]
	if s[i] == 'b' or s[i] == '?':
		incr0 += d0[i]
		incra += da[i]
		incrab += dab[i] + da[i]
		incrabc += dabc[i]
	if s[i] == 'c' or s[i] == '?':
		incr0 += d0[i]
		incra += da[i]
		incrab += dab[i]
		incrabc += dabc[i] + dab[i]
	d0.append(incr0 % M)
	da.append(incra % M)
	dab.append(incrab % M)
	dabc.append(incrabc % M)
print(dabc[l])


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
MOD = 1000000007

def main():
	n = int(input())
	s = input()
	dp = [0, 0, 0]
	v = 1
	for c in s:
		if c == 'a':
			dp[0] += v
		elif c == 'b':
			dp[1] += dp[0]
		elif c == 'c':
			dp[2] += dp[1]
		else:
			dp[2] = dp[2] * 3 + dp[1]
			dp[1] = dp[1] * 3 + dp[0]
			dp[0] = dp[0] * 3 + v
			v *= 3
		dp[0] %= MOD
		dp[1] %= MOD
		dp[2] %= MOD
		v %= MOD
	print(dp[2])
main()


from sys import stdin, stdout
MOD = 10 ** 9 + 7

def find(arr, N):
	R = [0, 0, 0]
	Z = 1
	for i in arr:
		if i == 'a':
			R[0] += Z
		if i == 'b':
			R[1] = (R[1] + R[0]) % MOD
		if i == 'c':
			R[2] = (R[2] + R[1]) % MOD
		if i == '?':
			(a, b, c) = (R[:], R[:], R[:])
			a[0] = (a[0] + Z) % MOD
			b[1] = (b[1] + b[0]) % MOD
			c[2] = (c[2] + c[1]) % MOD
			R = [(a[i] + b[i] + c[i]) % MOD for i in range(3)]
			Z = Z * 3 % MOD
	return R[2] % MOD

def main():
	N = int(stdin.readline())
	arr = stdin.readline().strip()
	print(find(arr, N))
main()


l = int(input())
s = input()
mod = 10 ** 9 + 7
dp = [[0, 0, 0, 0] for _ in range(l + 1)]
for i in range(l, -1, -1):
	for j in range(3, -1, -1):
		if i == l:
			if j == 3:
				dp[i][j] = 1
			else:
				dp[i][j] = 0
		else:
			if s[i] == '?':
				dp[i][j] = dp[i + 1][j] * 3
			else:
				dp[i][j] = dp[i + 1][j]
			if j != 3 and (s[i] == '?' or s[i] == 'abc'[j]):
				dp[i][j] += dp[i + 1][j + 1]
		dp[i][j] %= mod
print(dp[0][0])


n = int(input())
s = input()
MOD = 1000000007
dp = [[0 for i in range(3)] for j in range(n + 1)]
cur = 1
for i in range(1, n + 1):
	if s[i - 1] == 'a' or s[i - 1] == '?':
		dp[i][0] += dp[i - 1][0] + cur
		dp[i][1] += dp[i - 1][1]
		dp[i][2] += dp[i - 1][2]
	if s[i - 1] == 'b' or s[i - 1] == '?':
		dp[i][0] += dp[i - 1][0]
		dp[i][1] += dp[i - 1][1] + dp[i - 1][0]
		dp[i][2] += dp[i - 1][2]
	if s[i - 1] == 'c' or s[i - 1] == '?':
		dp[i][0] += dp[i - 1][0]
		dp[i][1] += dp[i - 1][1]
		dp[i][2] += dp[i - 1][2] + dp[i - 1][1]
	if s[i - 1] == '?':
		cur = cur * 3 % MOD
	dp[i][0] %= MOD
	dp[i][1] %= MOD
	dp[i][2] %= MOD
print(dp[n][2])


input()
o = a = b = 0
v = 1
M = 10 ** 9 + 7
for c in input():
	if c == 'a':
		a += v
	elif c == 'b':
		b += a
	elif c == 'c':
		o += b
	else:
		(a, b, o, v) = ((3 * a + v) % M, (3 * b + a) % M, (3 * o + b) % M, 3 * v % M)
print(o % M)


def main():
	n = eval(input())
	s = input()
	mod = 1000000007
	a = 0
	b = 0
	ab = 0
	sz = 1
	ans = 0
	for c in s:
		if c == 'a':
			a = a + sz
			a = a % mod
		elif c == 'b':
			ab = ab + a
			ab = ab % mod
		elif c == 'c':
			ans = ans + ab
			ans = ans % mod
		else:
			ans = (ans * 3 + ab) % mod
			ab = (ab * 3 + a) % mod
			a = (a * 3 + sz) % mod
			sz = sz * 3 % mod
	print(ans)
main()


p = 10 ** 9 + 7

def power(x, y, p):
	b = bin(y)[2:]
	start = x
	answer = 1
	for i in range(len(b) - 1, -1, -1):
		if b[i] == '1':
			answer = answer * start % p
		start = start * start % p
	return answer

def process(S):
	start = {'a': 0, '?': 0, 'ab': 0, '?b': 0, 'a?': 0, '??': 0, 'abc': 0, 'ab?': 0, 'a?c': 0, '?bc': 0, 'a??': 0, '?b?': 0, '??c': 0, '???': 0}
	ones = ['a', '?']
	twos = ['ab', '?b', 'a?', '??']
	question_count = 0
	n = len(S)
	answer = 0
	for i in range(n):
		c = S[i]
		if c == 'c' or c == '?':
			for x in twos:
				start[x + c] += start[x]
		if c == 'b' or c == '?':
			for x in ones:
				start[x + c] += start[x]
		if c == 'a' or c == '?':
			start[c] += 1
		if c == '?':
			question_count += 1
	for x in start:
		if len(x) == 3:
			q2 = 0
			for c in x:
				if c == '?':
					q2 += 1
			answer += start[x] * power(3, question_count - q2, p)
			answer = answer % p
	return answer
n = int(input())
S = input()
print(process(S))


import sys
readline = sys.stdin.readline
N = readline()
S = readline().strip()
mod = 10 ** 9 + 7
dp = [1] + [0] * 3
for s in S:
	dp1 = dp[:]
	if s == 'a':
		dp1[1] += dp[0]
	elif s == 'b':
		dp1[2] += dp[1]
	elif s == 'c':
		dp1[3] += dp[2]
	else:
		dp1[1] += dp[0]
		dp1[2] += dp[1]
		dp1[3] += dp[2]
		dp1[0] += 2 * dp[0]
		dp1[1] += 2 * dp[1]
		dp1[2] += 2 * dp[2]
		dp1[3] += 2 * dp[3]
	dp = [d % mod for d in dp1]
print(dp[-1])


from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush, heappop, heapify
import math
from collections import *
from functools import reduce, cmp_to_key
import sys
input = sys.stdin.readline
from itertools import accumulate
from functools import lru_cache
M = mod = 10 ** 9 + 7

def factors(n):
	return sorted(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))))

def inv_mod(n):
	return pow(n, mod - 2, mod)

def li():
	return [int(i) for i in input().rstrip('\n').split()]

def st():
	return input().rstrip('\n')

def val():
	return int(input().rstrip('\n'))

def li2():
	return [i for i in input().rstrip('\n')]

def li3():
	return [int(i) for i in input().rstrip('\n')]
n = val()
l = list(st())
questions1 = [0]
As = [0]
Cs = [0]
questions2 = [0]
for i in range(n):
	questions1.append(questions1[-1])
	if l[i] == '?':
		questions1[-1] += 1
	As.append(As[-1])
	if l[i] == 'a':
		As[-1] += 1
for i in range(n - 1, -1, -1):
	questions2.append(questions2[-1])
	if l[i] == '?':
		questions2[-1] += 1
	Cs.append(Cs[-1])
	if l[i] == 'c':
		Cs[-1] += 1
Cs.pop()
questions2.pop()
Cs.reverse()
questions2.reverse()
ans = 0
for i in range(n):
	if l[i] == 'b' or l[i] == '?':
		left = right = 0
		left = As[i] * pow(3, questions1[i], mod) % mod
		if questions1[i]:
			left = (left + pow(3, questions1[i] - 1, mod) * questions1[i]) % mod
		right = Cs[i] * pow(3, questions2[i], mod) % mod
		if questions2[i]:
			right = (right + pow(3, questions2[i] - 1, mod) * questions2[i]) % mod
		ans = (ans + left * right) % mod
print(ans)


mod = 1000000007
eps = 10 ** (-9)

def main():
	import sys
	input = sys.stdin.readline
	N = int(input())
	S = input().rstrip('\n')
	a_num = [0] * (N + 1)
	q_num_left = [0] * (N + 1)
	for (i, s) in enumerate(S):
		a_num[i + 1] = a_num[i]
		q_num_left[i + 1] = q_num_left[i]
		if s == 'a':
			a_num[i + 1] += 1
		if s == '?':
			q_num_left[i + 1] += 1
	S_rev = S[::-1]
	c_num = [0] * (N + 1)
	q_num_right = [0] * (N + 1)
	for (i, s) in enumerate(S_rev):
		c_num[i + 1] = c_num[i]
		q_num_right[i + 1] = q_num_right[i]
		if s == 'c':
			c_num[i + 1] += 1
		if s == '?':
			q_num_right[i + 1] += 1
	ans = 0
	k = q_num_left[-1]
	k0 = pow(3, k, mod)
	k1 = pow(3, max(0, k - 1), mod)
	k2 = pow(3, max(0, k - 2), mod)
	k3 = pow(3, max(0, k - 3), mod)
	for (i, s) in enumerate(S):
		if s == 'b':
			ans = (ans + a_num[i] * c_num[N - i - 1] % mod * k0 % mod) % mod
			ans = (ans + q_num_left[i] * c_num[N - i - 1] % mod * k1 % mod) % mod
			ans = (ans + a_num[i] * q_num_right[N - i - 1] % mod * k1 % mod) % mod
			ans = (ans + q_num_left[i] * q_num_right[N - i - 1] % mod * k2 % mod) % mod
		elif s == '?':
			ans = (ans + a_num[i] * c_num[N - i - 1] % mod * k1 % mod) % mod
			ans = (ans + q_num_left[i] * c_num[N - i - 1] % mod * k2 % mod) % mod
			ans = (ans + a_num[i] * q_num_right[N - i - 1] % mod * k2 % mod) % mod
			ans = (ans + q_num_left[i] * q_num_right[N - i - 1] % mod * k3 % mod) % mod
	print(ans)
main()


mod = 1000000007
n = int(input())
s = input()
p = s.count('?')
total = pow(3, p, mod)
inv_3 = pow(3, mod - 2, mod)
q = inv_3 * total % mod
count_c = [0] * (n + 1)
for i in range(n - 1, -1, -1):
	if s[i] == '?':
		count_c[i] = (count_c[i + 1] + q) % mod
	elif s[i] == 'c':
		count_c[i] = (count_c[i + 1] + total) % mod
	else:
		count_c[i] = count_c[i + 1]
count_bc = [0] * (n + 1)
for i in range(n - 1, -1, -1):
	if s[i] == '?':
		count_bc[i] = (count_bc[i + 1] + count_c[i + 1] * inv_3) % mod
	elif s[i] == 'b':
		count_bc[i] = (count_bc[i + 1] + count_c[i + 1]) % mod
	else:
		count_bc[i] = count_bc[i + 1]
count_abc = [0] * (n + 1)
for i in range(n - 1, -1, -1):
	if s[i] == '?':
		count_abc[i] = (count_abc[i + 1] + count_bc[i + 1] * inv_3) % mod
	elif s[i] == 'a':
		count_abc[i] = (count_abc[i + 1] + count_bc[i + 1]) % mod
	else:
		count_abc[i] = count_abc[i + 1]
print(count_abc[0])


import sys

def mmul(a, b, m):
	return a % m * (b % m) % m

def madd(a, b, m):
	return (a % m + b % m) % m

def mdiv(a, b, m):
	a = a % m
	inv = pow(b, m - 2, m)
	return inv * a % m
n = int(sys.stdin.readline())
s = sys.stdin.readline().strip()
mod = pow(10, 9) + 7
pre_a = [0]
pre_b = [0]
pre_c = [0]
pre_q = [0]
for i in range(n):
	c_a = 0
	c_b = 0
	c_c = 0
	c_q = 0
	if s[i] == 'a':
		c_a = 1
	elif s[i] == 'b':
		c_b = 1
	elif s[i] == 'c':
		c_c = 1
	elif s[i] == '?':
		c_q = 1
	pre_a.append(c_a + pre_a[i])
	pre_b.append(c_b + pre_b[i])
	pre_c.append(c_c + pre_c[i])
	pre_q.append(c_q + pre_q[i])
tot = pre_q[n]
ans = 0
for j in range(n):
	A = pre_a[j] - pre_a[0]
	X = pre_q[j] - pre_q[0]
	C = pre_c[n] - pre_c[j + 1]
	Y = pre_q[n] - pre_q[j + 1]
	val = 0
	val1 = 0
	val2 = 0
	val3 = 0
	if s[j] == 'b':
		if tot - 1 >= 0:
			val = mmul(pow(3, tot - 1, mod), mmul(X, C, mod), mod)
			val1 = mmul(pow(3, tot - 1, mod), mmul(A, Y, mod), mod)
		if tot - 2 >= 0:
			val2 = mmul(pow(3, tot - 2, mod), mmul(X, Y, mod), mod)
		val3 = mmul(pow(3, tot, mod), mmul(A, C, mod), mod)
	elif s[j] == '?':
		if tot - 1 >= 0:
			val = mmul(pow(3, tot - 1, mod), mmul(A, C, mod), mod)
		if tot - 2 >= 0:
			val1 = mmul(pow(3, tot - 2, mod), mmul(X, C, mod), mod)
			val2 = mmul(pow(3, tot - 2, mod), mmul(A, Y, mod), mod)
		if tot - 3 >= 0:
			val3 = mmul(pow(3, tot - 3, mod), mmul(X, Y, mod), mod)
	ans = madd(ans, val, mod)
	ans = madd(ans, val1, mod)
	ans = madd(ans, val2, mod)
	ans = madd(ans, val3, mod)
print(ans)


mod = 10 ** 9 + 7
n = int(input())
s = input()[::-1]
dp = [[0] * 3 for _ in range(n + 1)]
pows = [1]
for i in range(n):
	pows.append(pows[-1] * 3 % mod)
cnt = 0
for i in range(n):
	if s[i] == 'a':
		dp[i + 1][0] += dp[i][0]
		dp[i + 1][1] += dp[i][1]
		dp[i + 1][2] += dp[i][2] + dp[i][1]
	elif s[i] == 'b':
		dp[i + 1][0] += dp[i][0]
		dp[i + 1][1] += dp[i][1] + dp[i][0]
		dp[i + 1][2] += dp[i][2]
	elif s[i] == 'c':
		dp[i + 1][0] += dp[i][0] + pows[cnt]
		dp[i + 1][1] += dp[i][1]
		dp[i + 1][2] += dp[i][2]
	elif s[i] == '?':
		dp[i + 1][0] += dp[i][0]
		dp[i + 1][1] += dp[i][1]
		dp[i + 1][2] += dp[i][2] + dp[i][1]
		dp[i + 1][0] += dp[i][0]
		dp[i + 1][1] += dp[i][1] + dp[i][0]
		dp[i + 1][2] += dp[i][2]
		dp[i + 1][0] += dp[i][0] + pows[cnt]
		dp[i + 1][1] += dp[i][1]
		dp[i + 1][2] += dp[i][2]
		cnt += 1
	dp[i + 1][0] %= mod
	dp[i + 1][1] %= mod
	dp[i + 1][2] %= mod
print(dp[n][2])


MOD = 10 ** 9 + 7
n = int(input())
s = input()
leftQ = [0 for i in range(n)]
rghtQ = [0 for i in range(n)]
leftA = [0 for i in range(n)]
rghtC = [0 for i in range(n)]
for i in range(1, n):
	leftQ[i] = leftQ[i - 1] + (1 if s[i - 1] == '?' else 0)
	leftA[i] = leftA[i - 1] + (1 if s[i - 1] == 'a' else 0)
for i in range(n - 2, -1, -1):
	rghtQ[i] = rghtQ[i + 1] + (1 if s[i + 1] == '?' else 0)
	rghtC[i] = rghtC[i + 1] + (1 if s[i + 1] == 'c' else 0)
ans = 0
for i in range(n):
	if s[i] == 'b' or s[i] == '?':
		ans += leftA[i] * rghtC[i] * pow(3, leftQ[i], MOD) * pow(3, rghtQ[i], MOD)
		if leftQ[i] > 0:
			ans += leftQ[i] * rghtC[i] * pow(3, leftQ[i] - 1, MOD) * pow(3, rghtQ[i], MOD)
		if rghtQ[i] > 0:
			ans += leftA[i] * rghtQ[i] * pow(3, leftQ[i], MOD) * pow(3, rghtQ[i] - 1, MOD)
		if leftQ[i] > 0 and rghtQ[i] > 0:
			ans += leftQ[i] * rghtQ[i] * pow(3, leftQ[i] - 1, MOD) * pow(3, rghtQ[i] - 1, MOD)
		ans %= MOD
print(ans)


n = int(input())
s = input()
aCount = 0
abCount = 0
total = 0
exp = -3
for x in s:
	if x == 'a':
		aCount += 3
	elif x == 'b':
		abCount += 3 * aCount
	elif x == 'c':
		total += 3 * abCount
	else:
		total += abCount
		abCount += aCount
		aCount += 1
		exp += 1
if exp < 0:
	for x in range(-exp):
		total //= 3
else:
	total *= pow(3, exp, 1000000007)
print(total % 1000000007)


import sys
read = lambda : sys.stdin.readline().strip()
readi = lambda : map(int, read().split())
mod = 1000000000 + 7
n = int(read())
arr = read()
a = ab = abc = 0
string_count = 1
for ch in arr:
	if ch == 'a':
		a = (a + string_count) % mod
	if ch == 'b':
		ab = (ab + a) % mod
	if ch == 'c':
		abc = (abc + ab) % mod
	if ch == '?':
		abc = (3 * abc + ab) % mod
		ab = (3 * ab + a) % mod
		a = (3 * a + string_count) % mod
		string_count = 3 * string_count % mod
print(abc)


from functools import cmp_to_key
from collections import deque
from heapq import heappush, heappop
from math import log, ceil
import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def ii():
	return int(inp())

def li(lag=0):
	l = list(map(int, inp().split()))
	if lag != 0:
		for i in range(len(l)):
			l[i] += lag
	return l

def mi(lag=0):
	matrix = list()
	for i in range(n):
		matrix.append(li(lag))
	return matrix

def sli():
	return list(map(str, inp().split()))

def print_list(lista, space=' '):
	print(space.join(map(str, lista)))

class UnionFind:

	def __init__(self, n):
		self.parent = list(range(n))
		self.size = [1] * n
		self.num_sets = n

	def find(self, a):
		to_update = []
		while a != self.parent[a]:
			to_update.append(a)
			a = self.parent[a]
		for b in to_update:
			self.parent[b] = a
		return self.parent[a]

	def merge(self, a, b):
		a = self.find(a)
		b = self.find(b)
		if a == b:
			return
		if self.size[a] < self.size[b]:
			(a, b) = (b, a)
		self.num_sets -= 1
		self.parent[b] = a
		self.size[a] += self.size[b]

	def set_size(self, a):
		return self.size[self.find(a)]

	def __len__(self):
		return self.num_sets

def bisect_left(a, x):
	left = 0
	right = len(a)
	while left < right:
		mid = (left + right) // 2
		if a[mid] < x:
			left = mid + 1
		else:
			right = mid
	return left

def bisect_right(a, x):
	left = 0
	right = len(a)
	while left < right:
		mid = (left + right) // 2
		if a[mid] > x:
			right = mid
		else:
			left = mid + 1
	return left

def bisect_elements(a, x):
	return bisect_right(a, x) - bisect_left(a, x)

def custom_sort(lista):

	def cmp(x, y):
		if x + y > y + x:
			return 1
		else:
			return -1
	return sorted(lista, key=cmp_to_key(cmp))
MOD = 10 ** 9 + 7
maxN = 10 ** 5
FACT = [0] * maxN

def add(x, y):
	return (x + y) % MOD

def multiply(x, y):
	return x * y % MOD

def power(x, y):
	if y == 0:
		return 1
	elif y % 2:
		return multiply(x, power(x, y - 1))
	else:
		a = power(x, y // 2)
		return multiply(a, a)

def inverse(x):
	return power(x, MOD - 2)

def divide(x, y):
	return multiply(x, inverse(y))

def allFactorials():
	FACT[0] = 1
	for i in range(1, maxN):
		FACT[i] = multiply(i, FACT[i - 1])

def coeffBinom(n, k):
	if n < k:
		return 0
	return divide(FACT[n], multiply(FACT[k], FACT[n - k]))

def primes(N):
	smallest_prime = [1] * (N + 1)
	prime = []
	smallest_prime[0] = 0
	smallest_prime[1] = 0
	for i in range(2, N + 1):
		if smallest_prime[i] == 1:
			prime.append(i)
			smallest_prime[i] = i
		j = 0
		while j < len(prime) and i * prime[j] <= N:
			smallest_prime[i * prime[j]] = min(prime[j], smallest_prime[i])
			j += 1
	return (prime, smallest_prime)

def gcd(a, b):
	(s, t, r) = (0, 1, b)
	(old_s, old_t, old_r) = (1, 0, a)
	while r != 0:
		quotient = old_r // r
		(old_r, r) = (r, old_r - quotient * r)
		(old_s, s) = (s, old_s - quotient * s)
		(old_t, t) = (t, old_t - quotient * t)
	return (old_r, old_s, old_t)

def create_graph(n, m, undirected=1, unweighted=1):
	graph = [[] for i in range(n)]
	if unweighted:
		for i in range(m):
			[x, y] = li(lag=-1)
			graph[x].append(y)
			if undirected:
				graph[y].append(x)
	else:
		for i in range(m):
			[x, y, w] = li(lag=-1)
			w += 1
			graph[x].append([y, w])
			if undirected:
				graph[y].append([x, w])
	return graph

def create_tree(n, unweighted=1):
	children = [[] for i in range(n)]
	if unweighted:
		for i in range(n - 1):
			[x, y] = li(lag=-1)
			children[x].append(y)
			children[y].append(x)
	else:
		for i in range(n - 1):
			[x, y, w] = li(lag=-1)
			w += 1
			children[x].append([y, w])
			children[y].append([x, w])
	return children

def create_edges(m, unweighted=0):
	edges = list()
	if unweighted:
		for i in range(m):
			edges.append(li(lag=-1))
	else:
		for i in range(m):
			[x, y, w] = li(lag=-1)
			w += 1
			edges.append([w, x, y])
	return edges

def dist(tree, n, A, B=-1):
	s = [[A, 0]]
	(massimo, massimo_nodo) = (0, 0)
	distanza = -1
	v = [-1] * n
	while s:
		(el, dis) = s.pop()
		if dis > massimo:
			massimo = dis
			massimo_nodo = el
		if el == B:
			distanza = dis
		for child in tree[el]:
			if v[child] == -1:
				v[child] = 1
				s.append([child, dis + 1])
	return (massimo, massimo_nodo, distanza)

def diameter(tree):
	(_, foglia, _) = dist(tree, n, 0)
	(diam, _, _) = dist(tree, n, foglia)
	return diam

def dfs(graph, n, A):
	v = [-1] * n
	s = [[A, 0]]
	v[A] = 0
	while s:
		(el, dis) = s.pop()
		for child in graph[el]:
			if v[child] == -1:
				v[child] = dis + 1
				s.append([child, dis + 1])
	return v

def bfs(graph, n, A):
	v = [-1] * n
	s = deque()
	s.append([A, 0])
	v[A] = 0
	while s:
		(el, dis) = s.popleft()
		for child in graph[el]:
			if v[child] == -1:
				v[child] = dis + 1
				s.append([child, dis + 1])
	return v

def connected(graph, n):
	v = dfs(graph, n, 0)
	for el in v:
		if el == -1:
			return False
	return True

def topological(graph, n):
	indegree = [0] * n
	for el in range(n):
		for child in graph[el]:
			indegree[child] += 1
	s = deque()
	for el in range(n):
		if indegree[el] == 0:
			s.append(el)
	order = []
	while s:
		el = s.popleft()
		order.append(el)
		for child in graph[el]:
			indegree[child] -= 1
			if indegree[child] == 0:
				s.append(child)
	if n == len(order):
		return (False, order)
	else:
		return (True, [])

def bipartite(graph, n):
	color = [-1] * n
	color[0] = 0
	s = [0]
	while s:
		el = s.pop()
		for child in graph[el]:
			if color[child] == color[el]:
				return False
			if color[child] == -1:
				s.append(child)
			color[child] = 1 - color[el]
	return True

def dijkstra(graph, n, A):
	dist = [float('inf') for i in range(n)]
	prev = [-1 for i in range(n)]
	dist[A] = 0
	pq = []
	heappush(pq, [0, A])
	while pq:
		[d_v, v] = heappop(pq)
		if d_v != dist[v]:
			continue
		for (to, w) in graph[v]:
			if dist[v] + w < dist[to]:
				dist[to] = dist[v] + w
				prev[to] = v
				heappush(pq, [dist[to], to])
	return (dist, prev)

def dijkstra_0_1(graph, n, A):
	dist = [float('inf') for i in range(n)]
	dist[A] = 0
	p = deque()
	p.append(A)
	while p:
		v = p.popleft()
		for (to, w) in graph[v]:
			if dist[v] + w < dist[to]:
				dist[to] = dist[v] + w
			if w == 1:
				q.append(to)
			else:
				q.appendleft(to)
	return dist

def floyd_warshall(graph, n):
	dist = [[float('inf') for _ in range(n)] for _ in range(n)]
	for i in range(n):
		dist[i][i] = 0
		for (child, d) in graph[i]:
			dist[i][child] = d
			dist[child][i] = d
	for k in range(n):
		for i in range(n):
			for j in range(j):
				dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
	return dist

def minimum_spanning_tree(edges, n):
	edges = sorted(edges)
	union_find = UnionFind(n)
	used_edges = list()
	for (w, x, y) in edges:
		if union_find.find(x) != union_find.find(y):
			union_find.merge(x, y)
			used_edges.append([w, x, y])
	return used_edges

def parents_children_root_unrooted_tree(tree, n, root=0):
	q = deque()
	visited = [0] * n
	parent = [-1] * n
	children = [[] for i in range(n)]
	q.append(root)
	while q:
		all_done = 1
		visited[q[0]] = 1
		for child in tree[q[0]]:
			if not visited[child]:
				all_done = 0
				q.appendleft(child)
		if all_done:
			for child in tree[q[0]]:
				if parent[child] == -1:
					parent[q[0]] = child
					children[child].append(q[0])
			q.popleft()
	return (parent, children)

def all_longest_path_passing_from_node(parent, children, n):
	q = deque()
	visited = [len(children[i]) for i in range(n)]
	downwards = [[0, 0] for i in range(n)]
	upward = [1] * n
	longest_path = [1] * n
	for i in range(n):
		if not visited[i]:
			q.append(i)
			downwards[i] = [1, 0]
	while q:
		node = q.popleft()
		if parent[node] != -1:
			visited[parent[node]] -= 1
			if not visited[parent[node]]:
				q.append(parent[node])
		else:
			root = node
		for child in children[node]:
			downwards[node] = sorted([downwards[node][0], downwards[node][1], downwards[child][0] + 1], reverse=True)[0:2]
	s = [node]
	while s:
		node = s.pop()
		if parent[node] != -1:
			if downwards[parent[node]][0] == downwards[node][0] + 1:
				upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][1])
			else:
				upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][0])
		longest_path[node] = downwards[node][0] + downwards[node][1] + upward[node] - min([downwards[node][0], downwards[node][1], upward[node]]) - 1
		for child in children[node]:
			s.append(child)
	return longest_path

def finding_ancestors(parent, queries, n):
	steps = int(ceil(log(n, 2)))
	ancestors = [[-1 for i in range(n)] for j in range(steps)]
	ancestors[0] = parent
	for i in range(1, steps):
		for node in range(n):
			if ancestors[i - 1][node] != -1:
				ancestors[i][node] = ancestors[i - 1][ancestors[i - 1][node]]
	result = []
	for (node, k) in queries:
		ans = node
		if k >= n:
			ans = -1
		i = 0
		while k > 0 and ans != -1:
			if k % 2:
				ans = ancestors[i][ans]
			k = k // 2
			i += 1
		result.append(ans)
	return result

def prefix_sum(arr):
	r = [0] * (len(arr) + 1)
	for (i, el) in enumerate(arr):
		r[i + 1] = r[i] + el
	return r

def nearest_from_the_left_smaller_elements(arr):
	n = len(arr)
	res = [-1] * n
	s = []
	for (i, el) in enumerate(arr):
		while s and s[-1] >= el:
			s.pop()
		if s:
			res[i] = s[-1]
		s.append(el)
	return res

def sliding_window_minimum(arr, k):
	res = []
	q = deque()
	for (i, el) in enumerate(arr):
		while q and arr[q[-1]] >= el:
			q.pop()
		q.append(i)
		while q and q[0] <= i - k:
			q.popleft()
		if i >= k - 1:
			res.append(arr[q[0]])
	return res
n = ii()
s = str(inp())
prea = [0] * n
sufc = [0] * n
prep = [0] * n
sufp = [0] * n
tre = [1] * n
for i in range(n):
	prea[i] = (prea[i - 1] if i != 0 else 0) + (1 if s[i] == 'a' else 0)
	prep[i] = (prep[i - 1] if i != 0 else 0) + (1 if s[i] == '?' else 0)
for i in range(n - 1, -1, -1):
	sufc[i] = (sufc[i + 1] if i != n - 1 else 0) + (1 if s[i] == 'c' else 0)
	sufp[i] = (sufp[i + 1] if i != n - 1 else 0) + (1 if s[i] == '?' else 0)
for i in range(1, n):
	tre[i] = multiply(tre[i - 1], 3)
c = 0
for i in range(1, n - 1):
	if s[i] in ['?', 'b']:
		A = multiply(prea[i - 1], tre[prep[i - 1]])
		A = add(A, multiply(prep[i - 1], tre[prep[i - 1] - 1]))
		C = multiply(sufc[i + 1], tre[sufp[i + 1]])
		C = add(C, multiply(sufp[i + 1], tre[sufp[i + 1] - 1]))
		c = add(c, multiply(A, C))
print(c)


mod = 10 ** 9 + 7
n = int(input())
s = input()
dp = [[0] * 4 for i in range(len(s) + 1)]
dp[len(s)][3] = 1
for i in range(len(s))[::-1]:
	for j in range(4)[::-1]:
		if s[i] == '?':
			dp[i][j] = dp[i + 1][j] * 3
		else:
			dp[i][j] = dp[i + 1][j]
		if j < 3:
			if s[i] == '?' or s[i] == 'abc'[j]:
				dp[i][j] += dp[i + 1][j + 1]
		dp[i][j] %= mod
print(dp[0][0])


n = int(input())
s = input()
a = 0
ab = 0
abc = 0
mod = 10 ** 9 + 7
qu = 1
for i in range(n):
	si = s[i]
	if si == 'a':
		a += qu
	elif si == 'b':
		ab += a
	elif si == 'c':
		abc += ab
	else:
		tmp1 = a
		tmp2 = ab
		a *= 3
		ab *= 3
		abc *= 3
		a += qu
		ab += tmp1
		abc += tmp2
		qu *= 3
		qu %= mod
	a %= mod
	ab %= mod
	abc %= mod
print(abc)


mod = 10 ** 9 + 7
n = int(input())
s = input()
em = 1
a = 0
ab = 0
abc = 0
for cur_c in s:
	new_em = 0
	new_a = 0
	new_ab = 0
	new_abc = 0
	opts = [cur_c]
	if cur_c == '?':
		opts = ['a', 'b', 'c']
	for c in opts:
		new_em += em
		new_a += a
		new_ab += ab
		new_abc += abc
		if c == 'a':
			new_a += em
		elif c == 'b':
			new_ab += a
		else:
			new_abc += ab
	em = new_em % mod
	a = new_a % mod
	ab = new_ab % mod
	abc = new_abc % mod
print(abc)


n = int(input())
s = ' ' + input()
F = [[-1 for i in range(4)] for j in range(n + 1)]
F[0] = [1, 0, 0, 0]
div = 10 ** 9 + 7
for i in range(1, n + 1):
	if s[i] == '?':
		F[i][0] = 3 * F[i - 1][0] % div
	else:
		F[i][0] = F[i - 1][0] % div
	if s[i] == 'a':
		F[i][1] = (F[i - 1][1] + F[i - 1][0]) % div
	elif s[i] == '?':
		F[i][1] = (3 * F[i - 1][1] + F[i - 1][0]) % div
	else:
		F[i][1] = F[i - 1][1] % div
	if s[i] == 'b':
		F[i][2] = (F[i - 1][2] + F[i - 1][1]) % div
	elif s[i] == '?':
		F[i][2] = (3 * F[i - 1][2] + F[i - 1][1]) % div
	else:
		F[i][2] = F[i - 1][2] % div
	if s[i] == 'c':
		F[i][3] = (F[i - 1][3] + F[i - 1][2]) % div
	elif s[i] == '?':
		F[i][3] = (3 * F[i - 1][3] + F[i - 1][2]) % div
	else:
		F[i][3] = F[i - 1][3] % div
print(F[-1][3])