【題解】ZeroJudge e507: 10252 – Common Permutation

【題目敘述】https://zerojudge.tw/ShowProblem?problemid=e507
【解題想法】分別統計字串 a 和字串 b中,26個小寫字母出現的頻率,取交集。

#include <iostream>
using namespace std;

string a, b;
int cnta[26], cntb[26];

int main() {
    while (cin >> a >> b){
        for (int i = 0; i < 26; i++){
            cnta[i] = 0;
            cntb[i] = 0;
        }
        for (int i = 0; i < a.length(); i++){
            cnta[a[i]-'a']++;
        }
        for (int i = 0; i < b.length(); i++){
            cntb[b[i]-'a']++;
        }
        for (int i = 0; i < 26; i++){
            for (int j = min(cnta[i], cntb[i]); j > 0; j--){
                cout << (char)('a'+i);
            }
        }
        cout << "\n";
    }
}

Python code (credit: Amy Chou)

while True:
    try:
        a = input()
        b = input()
        cntA = [0 for _ in range(26)]
        for i in range(len(a)):
            cntA[ord(a[i]) - 97] += 1

        cntB = [0 for _ in range(26)]
        for i in range(len(b)):
            cntB[ord(b[i]) - 97] += 1

        ans = ""
        for i in range(26):
            ans += chr(i+97) * min(cntA[i], cntB[i])
        print(ans)
    except:
        break

分享本文 Share with friends