解説
文字列の列 が再帰的頭字語であるとき、 のそれぞれの 文字目をこの順に連結した文字列は のいずれかの要素に一致します。
ここで、ある文字列 について、 に含まれる文字 の数を とおいて、 とします。
すると、次のようなアルゴリズムでこの問題を解くことができます。
- 空の集合を用意する。
- について以下を行う。
- を計算して集合に追加する。
- のそれぞれの 文字目をこの順に連結した文字列を として、集合に が含まれるなら
Yes、含まれないならNoと出力する。
実装の際は、順序付き集合を扱うデータ構造を用いると良いです。 計算量は文字種数を として です。
実装例(C++)
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> top(26);
set<vector<int>> st;
for (int i = 0; i < n; i++) {
string s;
cin >> s;
top[s[0]-'a']++;
vector<int> cnt(26);
for (char c : s) cnt[c-'a']++;
st.insert(cnt);
cout << (st.count(top) ? "Yes" : "No") << '\n';
}
}
実装例(Python)
# https://github.com/tatyam-prime/SortedSet/blob/main/SortedSet.py
n = int(input())
top = [0] * 26
st = SortedSet()
s = list(input().split())
for i in range(n):
top[ord(s[i][0])-ord('a')] += 1
cnt = [0] * 26
for c in s[i]:
cnt[ord(c)-ord('a')] += 1
st.add(cnt)
print("Yes" if top in st else "No")
ユーザー解説
ユーザー解説を書くユーザー解説はまだありません。