1. 程式人生 > 實用技巧 >Huawei機試系列(5)

Huawei機試系列(5)

記票統計

問題描述詳見記票統計

while True:
    try:
        candidateNum = int(input())
        candidate = input().split()
        voterNum = int(input())
        vote = input().split()
        result = []
        for elem in candidate:
            result.append(vote.count(elem))
        for i,elem in enumerate(candidate):
            print("{0} : {1}".format(elem,str(result[i])))
        print("Invalid : " + str(voterNum -sum(result)))
    except:
        break

表示數字

問題描述詳見將一個字元中所有出現的數字前後加上符號“*”,其他字元保持不變

while True:
    try:
        string = list(input())
        ans = ""
        for ch in string:
            if (ch.isdigit()):
                ans += '*' + ch + '*'
            else:
                ans+=ch
        print(ans.replace("**",""))
    except:
        break

字元統計

問題描述詳見字元統計

自定義結構體版
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
struct foo
{
	char ch;
	int count;
	foo(char ch) :ch(ch), count(1) {}
	bool operator >(const foo& f)const
	{	
		 if(count == f.count)
			return ch < f.ch;
		 else
			 return count > f.count;
	}
	bool operator ==(const foo& f)const
	{
		return ch == f.ch;
	}
};
int main()
{
	string str;
	while (cin >> str)
	{
		vector<foo> vec;
		for (auto elem : str)
		{
			auto it = find(vec.begin(), vec.end(), foo(elem));
			if (it == vec.end())
				vec.emplace_back(foo(elem));
			else
				(*it).count += 1;
		}
		sort(vec.begin(), vec.end(),greater<foo>());
		for (auto f : vec)
			cout << f.ch;
		cout << endl;
	}
}
STL map精簡版
#include<iostream> 
#include<string> 
#include<vector> 
#include<algorithm> 
#include<map> 
using namespace std;
int main(){
	string str;
	while (cin >> str){
		map<char, int> m;
		for (auto s : str)	++m[s];  //map下標訪問
		vector<pair<char, int>> vec(m.begin(), m.end());
		stable_sort(vec.begin(), vec.end(), [](const pair<char, int> &p1, const pair<char, int> &p2)  //穩定排序,匿名函式
		{return p1.second > p2.second; });
		for (auto p : vec) cout << p.first;
		cout << endl;
	}
}