2018华为校招软件,c++做了两道不知道对不对

  1. 字符替换

    #include<iostream>
    #include<string>
    #include<math.h>
    #include<vector>
    using namespace std;
    int main()
    {
     vector vsit;
     char ch1 = '9', ch2 = '8';
     string str = "9897899";
     string str1 = str;
     cout << str;
     int num = 0;
     num = count(str1.begin(), str1.end(), ch1);
     size_t strIter = str1.size();
     while(strIter) {        
         strIter = str1.rfind(ch1,strIter-1);
         vsit.push_back(strIter);
     }
     //vector中存放目标的位置    
     for (int i = 1; i <pow(2,num); i++) {
         int n = 0, count = 0, j = i;
         str1 = str;
         while (j) {
             j = j >> 1;
             count++;
         }//统计出二进制的位数
         while (count >= n+1) {
             if (i & int(pow(2, n++))) {        
                 str1[vsit[n - 1]] = ch2;                
             }                
         }
         cout << "," << str1;        
     }
     system("pause");
    }
  2. 数字统计
    #include<iostream>
    #include<string>
    #include<vector>
    #include<cctype>
    #include<algorithm>
    #include<map>
    using namespace std;
    {
    vector<int> vs;
    string str = "5 2 4 5 56 56 8 9 2 3 4 5 6 3 45 5 56 9 0 9 9 0 9 0 9 0 8 2123 2123 223 223 2123 223 2123 8 9 8";
    string str1;
    int num = 0;
    map<int, int> numMap;
    for (auto i : str) {
        if (isdigit(i))
            str1 += i;
        else {
            num = stoi(str1);
            vs.push_back(num);
            str1 = "";
        }
    }    
    num = stoi(str1);
    vs.push_back(num);
    sort(vs.begin(), vs.end());
    for (auto j : vs) {        
        numMap[j] += 1;
    }
    auto map_it = numMap.cbegin();
    string ch1, ch2;
    int n = 0;
    while (map_it != numMap.cend()) {
        ch1 = to_string(map_it->first);
        ch2 = to_string(map_it->second);
        if(!n)
            cout << ch1 << " " << ch2 << " ";
        else
            cout << " " << ch1 << " " << ch2 << " ";
        ++map_it;
        n++;
    }
    system("pause");
    }
#华为#
全部评论
#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]); }
点赞 回复 分享
发布于 2017-09-20 22:54

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务