2025年7月3日 星期四

ZeroJudge 解題筆記:a224. 明明愛明明

作者:王一哲
日期:2025年7月3日


ZeroJudge 題目連結:a224. 明明愛明明

解題想法


先將所有字母轉成小寫,再用字典或表格計數,計算每個字母出現的次數,同時計算所有字母的數量 n。如果 n 是奇數,只能有一個字母的數量是奇數;如果 n 是偶數,所有的字母數量都必須是偶數。

Python 程式碼


寫法1,字典計數,使用時間約為 22 ms,記憶體約為 3.6 MB,通過測試。
import sys
from collections import defaultdict

def check(s):
    n = 0
    cnt = defaultdict(int)
    for c in s.lower():
        n += 1
        if c.isalpha():
            cnt[c] += 1
    even = sum(v%2 for v in cnt.values())
    if n%2 == 1:
        return even <= 1
    else:
        return even == 0

for line in sys.stdin:
    print("yes !" if check(line.rstrip()) else "no...")

寫法2,表格計數,使用時間約為 19 ms,記憶體約為 3.3 MB,通過測試。
import sys

def check(s):
    n = 0
    cnt = [0]*26
    for c in s.lower():
        n += 1
        if c.isalpha():
            cnt[ord(c)-ord('a')] += 1
    even = sum(v%2 for v in cnt)
    if n%2 == 1:
        return even <= 1
    else:
        return even == 0

for line in sys.stdin:
    print("yes !" if check(line.rstrip()) else "no...")


C++ 程式碼


寫法1,字典計數,使用時間約為 2 ms,記憶體約為 352 kB,通過測試。
#include <iostream>
#include <string>
#include <map>
#include <cctype>
using namespace std;

bool check(string s) {
    int n = 0;
    map<char, int> cnt;
    for(char c : s) {
        if (isalpha(c)) {
            n++;
            cnt[tolower(c)]++;
        }
    }
    int even = 0;
    for(auto it : cnt) {
        if (it.second % 2 == 1) {
            even++;
        }
    }
    if (n%2 == 1) return even <= 1;
    else return even == 0;
}

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    string line;
    while(getline(cin, line)) cout << (check(line) ? "yes !\n" : "no...\n");
    return 0;
}

寫法2,表格計數,使用時間約為 2 ms,記憶體約為 312 kB,通過測試。
#include <iostream>
#include <string>
using namespace std;

bool check(string s) {
    int n = 0, cnt[26] = {0};
    for(char c : s) {
        if (c >= 'a' && c <= 'z') {
            n++;
            cnt[c-'a']++;
        } else if (c >= 'A' && c <= 'Z') {
            n++;
            cnt[c-'A']++;
        }
    }
    int even = 0;
    for(int i=0; i<26; i++) {
        if (cnt[i]%2 == 1) {
            even++;
        }
    }
    if (n%2 == 1) return even <= 1;
    else return even == 0;
}

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    string line;
    while(getline(cin, line)) cout << (check(line) ? "yes !\n" : "no...\n");
    return 0;
}


沒有留言:

張貼留言