微软2014机试第一题

来源:互联网 发布:python dll 编辑:程序博客网 时间:2024/05/21 06:32
Description
For this question, your program is required to process an input string containing only ASCII characters between ‘0’ and ‘9’, or between ‘a’ and ‘z’ (including ‘0’, ‘9’, ‘a’, ‘z’).
 
Your program should reorder and split all input string characters into multiple segments, and output all segments as one concatenated string. The following requirements should also be met,
1. Characters in each segment should be in strictly increasing order. For ordering, ‘9’ is larger than ‘0’, ‘a’ is larger than ‘9’, and ‘z’ is larger than ‘a’ (basically following ASCII character order).
2. Characters in the second segment must be the same as or a subset of the first segment; and every following segment must be the same as or a subset of its previous segment.
 
Your program should output string “<invalid input string>” when the input contains any invalid characters (i.e., outside the '0'-'9' and 'a'-'z' range).
 
 Input
 
Input consists of multiple cases, one case per line. Each case is one string consisting of ASCII characters.
 
Output
 
For each case, print exactly one line with the reordered string based on the criteria above.
 
 样例输入
aabbccdd
007799aabbccddeeff113355zz
1234.89898
abcdefabcdefabcdefaaaaaaaaaaaaaabbbbbbbddddddee样例输出
abcdabcd
013579abcdefz013579abcdefz
<invalid input string>
abcdefabcdefabcdefabdeabdeabdabdabdabdabaaaaaaa
 
 
代码能力较弱,我就大致表述下想法,对于很多涉及到重复字符串的题目,感觉很自然能想到散列表。对于这道题,我的想法就是
①做一个含有36个元素的一维数组hashkey[36],分别对用0-9,a-z的字符的个数,先初始化为0
②扫描字符串,比如扫到'1',就在hashkey[1]加一,扫到’'a'就在hashkey[10]加1
③多次从头到尾扫描hashkey,扫一次过程中将hashkey值不为0的字符填入带输出字符串中,并且将hashkey减一,直到待输出字符串的长度等于输出字符串的长度
 
 
代码如下
#include<stdio.h>#include<string.h>void paixu(char input[],int len,int hashkey[]){int i,j,temp;for(i=0;i<36;i++){    hashkey[i]=0;}for(i=0;i<len;i++){if( (input[i]>='0' && input[i]<='9') ){    temp = input[i] - '0';    hashkey[temp]++;}else if( input[i]>='a' && input[i]<='z'){    temp = input[i] - 'a' + 10;    hashkey[temp]++;}else{    printf("<invalid input string>\n") ;    return ;}}i=0;while(i<len){j=0;while(i<len && j<36){ if( hashkey[j] != 0 ){    hashkey[j]--;    if(j<10)    {    input[i++]=j+'0';    }    else    {    input[i++]= j - 10 +'a';    }}j++;}}input[i]='\0';         puts(input) ;}int main(){int hash_key[36];char inp[1024];int i;int temp;while(1){gets(inp);int len =strlen(inp);         paixu(inp, len,hash_key);}}

 
0 0