Problem:
Score : 700 points

Problem Statement

You are given a string S consisting of a,b and c. Find the number of strings that can be possibly obtained by repeatedly performing the following operation zero or more times, modulo 998244353:

Choose an integer i such that 1\leq i\leq |S|-1 and the i-th and (i+1)-th characters in S are different. Replace each of the i-th and (i+1)-th characters in S with the character that differs from both of them (among a, b and c).

Constraints

2 \leq |S| \leq 2 × 10^5

S consists of a, b and c.

Input

Input is given from Standard Input in the following format:

S

Output

Print the number of strings that can be possibly obtained by repeatedly performing the operation, modulo 998244353.

Sample Input 1

abc

Sample Output 1

3

abc, aaa and ccc can be obtained.

Sample Input 2

abbac

Sample Output 2

65

Sample Input 3

babacabac

Sample Output 3

6310

Sample Input 4

ababacbcacbacacbcbbcbbacbaccacbacbacba

Sample Output 4

148010497

Solution in Ruby (2.3.3) (judge verdict: Accepted)

S = gets.chomp
N = S.length

cnt = Hash.new(0)
init = 1
N.times do |i|
    cnt[S[i]] += 1
    init = 0 if i > 0 && S[i-1] == S[i]
end
if cnt.length == 1
    puts 1
    exit
end

mod = (cnt['b'] + cnt['c'] * 2) % 3
if N == 3
    puts mod == 0 ? 3 : 6 + init
    exit
end

MOD = 998244353

dp = Array.new(N){Array.new(3){Array.new(3, 0)}}
3.times do |j|
    dp[0][j][j] = 1
end

(N-1).times do |i|
    3.times do |j|
        3.times do |k|
            3.times do |add|
                next if k == add
                dp[i+1][(j+add)%3][add] += dp[i][j][k]
                dp[i+1][(j+add)%3][add] %= MOD
            end
        end
    end
end

bad = 0
3.times do |j|
    3.times do |k|
        3.times do |add|
            next if k == add || (j+add)%3 != mod
            bad += dp[N-2][j][k]
            bad %= MOD
        end
    end
end

puts (3**(N-1) - bad + init) % MOD