問題
S1,...,Sn のどの文字列が書かれていても作れる文字列のうち、最長のものを求めてください。 最長のものが複数ある場合は、辞書順で最小のものを求めてください。
考察
入力される文字列すべてにおいて英字aが何回出てくるか数えて、最も出現回数の少ないものを出力する
例えば
A aabb
B ab
C aabbb
があるとする。
まず、文字aが文字列ABCの中で出現回数が一番小さい文字列を確定させる。
文字列Bが一回だけaがでてくるので、aが出力される。
これをa ~ zまで繰り返していくと、辞書順に最長文字列を得ることができる
コード
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
string s[60] = {};
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> s[i];
}
string ans;
for (char c = 'a'; c <= 'z'; c++)
{
int small = 100;
for (int i = 0; i < n; i++)
{
int cnt = 0;
for (int j = 0; j < s[i].length(); j++)
{
if (s[i][j] == c)cnt++;
}
small = min(small, cnt);
}
for (int i = 0; i < small; i++)
{
ans += c;
}
}
cout << ans << endl;
return 0;
}
ポイント
①charのループで文字列判定を行う
このループ判定は良く使うので覚えておく!
良い問題でした。