微软2014实习生及秋令营技术类职位在线测试——String reorder

来源:互联网 发布:索尼c6802怎么清除数据 编辑:程序博客网 时间:2024/05/16 17:21

【来源】

题目1 : String reorder

【分析】
统计各个字符出现的次数,然后一遍遍地遍历输出。
【代码】
#include <iostream>#include <string>using namespace std;int main(){    int times[36];    for (int i = 0; i < 36; ++i){        times[i] = 0;    }    string s;    while (getline(cin, s)){        for (int i = 0; i < s.size(); ++i){            bool valid = s[i] >= '0' && s[i] <= '9' || s[i] >= 'a' && s[i] <= 'z';            if (!valid){                cout << "<invalid input string>" << endl;                break;            }            if (s[i] >= '0' && s[i] <= '9'){                ++times[s[i] - '0'];            }            if (s[i] >= 'a' && s[i] <= 'z'){                ++times[s[i] - 'a' + 10];            }        }        string out = "";        while (true){            int countz = 0;            for (int i = 0; i < 36; ++i){                if (!times[i]){                    ++countz;                }            }            if (countz == 36){                break;            }            for (int i = 0; i < 10; ++i){                if (times[i] > 0){                    out += (i + '0');                    --times[i];                }            }            for (int i = 10; i < 36; ++i){                if (times[i] > 0){                    out += char(i - 10 + 'a');                    --times[i];                }            }        }        cout << out << endl;    }    system("pause");    return 0;}

【点评】
简单题。

【备注】

本代码未经过OJ提交测试,如有问题欢迎讨论。


0 0