# Hash Table# String# Counting

e706 - 12820 - Cool Word

🔗 前往 ZeroJudge 原題

題目描述

題目要求計算給定單詞列表中 "cool word" 的數量。"cool word" 的定義是,單詞中至少包含兩個不同的字母,且每個不同字母的出現次數都不同。

解題思路

對於每個單詞,我們需要統計每個字母出現的次數。可以使用一個大小為 26 的陣列 c 來儲存每個小寫字母的出現次數。然後,我們計算不同字母的數量 chat。如果 chat 小於 2,則該單詞不是 "cool word",直接跳過。接著,我們檢查是否存在兩個不同字母的出現次數相同。如果存在,則該單詞不是 "cool word"。如果不存在,則該單詞是 "cool word",計數器 ans 增加。

複雜度分析

  • 時間複雜度: O(N * M),其中 N 是單詞列表的長度,M 是單詞的最大長度。對於每個單詞,我們需要遍歷其所有字母來統計字母出現次數,以及遍歷 26 個字母來檢查出現次數是否相同。
  • 空間複雜度: O(1),因為我們使用的陣列 c 的大小是固定的 (26)。

程式碼

#include <iostream>
#include <string>
using namespace std;
int main(){
	int a,i=1;
	string b;
	while(cin >> a){
		int ans=0;
		while(a--){
		cin >> b;
		if(b.length()==1)continue;
		int c[26]={0},chat=0;
		bool t=0;
		for(int i=b.length()-1;i>=0;i--)
			c[b[i]-97]++;
		for(int i=0;i<26;i++)
			if(c[i]!=0)
				chat++;
		if(chat==1)continue;	
		for(int i=0;i<26&&t==0;i++)
			for(int j=i+1;j<26&&t==0;j++)
				if(c[i]==c[j]&&c[i]!=0)
					t=1;
		if(t==0)ans++;
		}
		cout << "Case " << i << ": " << ans << "\n";
		i++;
	}
}

Discussion