华为软件开发编程题统计数字(80%)+字符替换(未知通过率)
1、统计数字,只有80%,感觉代码还可以,借助哈希,无需用到set,vector等容器
#include<iostream>
#include<string>
using namespace std;
int main()
{
int record[10] = { 0 };
string s;
while (getline(cin, s)) {
for (unsigned int i = 0; i<s.size(); i++) {
record[s[i] - 48]++;
}
int lastone = 9;
while (record[lastone--] == 0);
lastone++;
for (int i = 0; i<lastone; i++) {
if (record[i] != 0) {
cout << i << " ";
cout << record[i] << " ";
}
}
cout << lastone << " " << record[lastone] << endl;
}
}
2、字符替换。交卷了才写好,没考虑大小写不敏感。
#include<string>
#include<iostream>
#include<vector>
using namespace std;
void replace(string &s, char torep, char rep,const vector<int> &vec,int index )
{
if (index == vec.size() )
cout << s<<",";
else {
replace(s, torep, rep, vec, index+1);
s[vec[index]] = rep;
replace(s, torep, rep, vec, index + 1);
s[vec[index]] = torep;
}
}
int main()
{
string s;
char torep,rep;
cin >> s >> torep >> rep;
vector<int> vec;
for (int i = 0; i < s.size(); i++) {
if (s[i] == torep)
vec.push_back(i);
}
replace(s, torep, rep,vec,vec[0]);
}