Official

B - 1122 String Editorial by en_translator


It is sufficient to check if the given string satisfies the three conditions for a 1122 string.
The third condition can be rephrased in any way, for example as follows, provided that the first and second are met, so we can use such rephrased condition. Here, \(S_i\) denotes the \(i\)-th character of \(S\).

  • \(S_1,S_3,\ldots, S_{|S|-1}\) are all distinct.
  • For each character \(S_i\) of \(S\), there is exactly two elements of \(S\) that coincides with that character.
    That is, for all integers \(i\) between \(1\) and \(|S|\), there are exactly two indices \(j\) \((1\leq j\leq |S|)\) with \(S_i=S_j\).

The complexity is \(O(\lvert S\rvert+C)\) in the original solution. Here, \(C\) is the number of distinct characters that may be used in \(S\); this time, \(C=26\). In the rephrased condition, naive implementation may cost \(O(\lvert S\rvert^2)\) time, but in our case \(\lvert S\rvert\leq 100\), which is acceptable. Therefore, the condition can be checked in any way, so the problem has been solved.

Sample code in C++:

#include <bits/stdc++.h>
using namespace std;

int main() {
	int n;
	string s;
	int cnt[26]={};
	bool flag=true;

	cin>>s;
	n=s.size();
	if(n%2==1)flag=false;
	if(flag){
		for(int i=0;i<(n/2);i++){
			if(s[2*i]!=s[2*i+1])flag=false;
		}
	}
	if(flag){
		for(int i=0;i<n;i++){
			cnt[s[i]-'a']++;
		}
		for(int i=0;i<26;i++){
			if((cnt[i]!=0)&&(cnt[i]!=2))flag=false;
		}
	}

	if(flag)cout<<"Yes"<<endl;
	else cout<<"No"<<endl;
	return 0;
}

Sample code in Python:

s=input()
flag=True

if len(s)%2==1:
    flag=False

if flag:
    for i in range(len(s)//2):
        if s[2*i]!=s[2*i+1]:
            flag=False

cnt=[0 for i in range(26)]
if flag:
    for i in range(len(s)):
        cnt[ord(s[i])-ord('a')]+=1
    for i in range(26):
        if cnt[i]!=0 and cnt[i]!=2:
            flag=False

if flag:
    print("Yes")
else:
    print("No")

posted:
last update: