微軟2014機試第一題

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);
	}	
}


 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章