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 C++14 (GCC 5.4.1) (judge verdict: Accepted)

#include <bits/stdc++.h>

using namespace std;

typedef long long LL;
typedef pair<int , int> P2;
typedef pair<pair<int , int> , int> P3;
typedef pair<pair<int , int> , pair<int , int> > P4;
#define PB(a) push_back(a)
#define MP(a , b) make_pair((a) , (b))
#define M3P(a , b , c) make_pair(make_pair((a) , (b)) , (c))
#define M4P(a , b , c , d) make_pair(make_pair((a) , (b)) , make_pair((c) , (d)))
#define repp(i,a,b) for(int i = (int)(a) ; i < (int)(b) ; ++i)
#define repm(i,a,b) for(int i = (int)(a) ; i > (int)(b) ; --i)

const LL mod = 998244353;
string S;
LL dp[200010][3][3];

int solve(){
	set<string> ans{S};
	queue<string> Q; Q.push(S);
	while(!Q.empty()){
		string x = Q.front(); Q.pop();
		repp(i,1,S.size()) if(x[i-1] != x[i]){
			string y = x;
			if(x[i-1] != 'a' && x[i] != 'a') y[i-1] = y[i] = 'a'; 
			else if(x[i-1] != 'b' && x[i] != 'b') y[i-1] = y[i] = 'b';
			else if(x[i-1] != 'c' && x[i] != 'c') y[i-1] = y[i] = 'c';
			if(ans.find(y) == ans.end()){
				Q.push(y);
				ans.insert(y);
			}
		}
	}
	return ans.size();
}

int main(){
	cin >> S;
	int n = S.size();
	if(n < 4){
		cout << solve() << endl;
		return 0;
	}
	int d = 0 , m = S[0] - 'a';
	repp(i,1,n){
		if(S[i-1] != S[i]) ++d;
		m += S[i] - 'a';
	}
	if(d == 0){
		cout << 1 << endl;
		return 0;
	}
	dp[1][0][0] = dp[1][1][1] = dp[1][2][2] = 1;
	repp(i,1,n) repp(j,0,3) repp(k,0,3) repp(l,0,3) if(k != l)
		(dp[i+1][(j+l)%3][l] += dp[i][j][k]) %= mod;
	LL ans = 1 , ans2 = 3 , t = 1;
	repp(i,1,n) (ans *= 3) %= mod;
	repp(i,2,n) (ans2 *= 2) %= mod;
	repp(j,0,3) repp(k,0,3) if((j+k)%3 == m%3) ans += dp[n-1][j][k];
	cout << (ans - ans2 + mod + (d==n-1?1:0)) % mod << endl;
	return 0;
}