[華爲OJ] 名字的漂亮度

思路:

1. 每個名字分別進行處理,將漂亮度結果存在數組中,最後打印;

2. 在處理某一個名字時,先對名字中出現的字母頻次進行統計;(根據題意,應該先將字母轉爲小寫,不過OJ上不轉也能過,用了tolower()反而錯了)

3. 對字母頻次進行排序,根據計算公式計算漂亮度;

4. 對結果進行輸出。(注意,這裏輸出需要換行,坑爹)


代碼:

#include <iostream>      
#include <string>  
#include <vector>
#include <algorithm>
using namespace std;    
      
void main(){      
    int num;
	cin >> num;
	vector<int> res(num,0);
	for(int i = 0; i < num; i++){
		string s;
		cin >> s;
		int size = s.size();
		vector<int> cnt(26,0);
		//統計名字中字母出現的頻次
		for(int j = 0; j < size; j++){ 
			//tolower(s[j]);			//全部轉換爲小寫,但是華爲OJ的這個平臺不知道爲什麼不能使用這個函數,加入這個代碼就錯了
			cnt[s[j] - 'a']++;      //注意:這裏不要寫成"a","a"代表一個字符串地址(內容爲a)
		}
		sort(cnt.begin(),cnt.end()); //從小到大排序
		//計算每個名字的漂亮度
		for(int m = 0; m < 26; m++){
			res[i] += (m + 1)*cnt[m];
		}
		
	}
	for(int t = 0; t < num; t++){
		cout << res[t] << " ";
	}
}    


發佈了26 篇原創文章 · 獲贊 1 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章