微软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.

#include <stdio.h>
#include <string.h>

#define MAXWORDS

int main ()
{
	char character[2][36] = {'0','1','2','3','4','5','6','7','8','9',
						  'a','b','c','d','e','f','g','h','i','j','k','l','m','n',
	                       'o','p','q','r','s','t','u','v','w','x','y','z'};
	int i, j;
	char c ,tmp_char, tmp_time;
	for (i = 0;i < 36;i++)
	{
		character[1][i] = '0';
	}
/*	for (i=0; i < 2; i++)
	{
		for (j = 0; j < 36; j++)
		{
			printf("%c ", character[i][j]);
		}
	} */

	printf("INPUT THE CHAR YOU WANT\n");
	while((c = getchar())!= '\n')
	{
		for (i = 0; i < 36; i++)
		{
			if ( c == character[0][i])
			{
				character[1][i]++;
			}
		}
	}

	//find the most number 
	tmp_time = character[1][0];
	for (i = 1; i < 36; i++)
	{
		if (character[1][i] > tmp_time )
		{
			tmp_time = character[1][i];
			tmp_char = character[0][i]; 
		}
	}

	printf("the most number is %c, the time is %c\n", tmp_char,tmp_time );

	for (i = 0; i < tmp_time; i++)
	{
		for (j = 0; j < 36; j++)
		{
			if (character[1][j] > '0')
			{
				printf("%c", character[0][j]);
				character[1][j]--;
			}
		}
	}


	return 0;
}

这次的方法跟上一篇完全不同,写起来很快。算法思想也很简单,为'0'~'9'和'a'~'z'这36个字符建立一个二维数组character[2][36];第一行将这36个字符存起来,第二行来记录这些字符出现的次数;

然后,找到出现最多的字符,并且找到他的出现次数tmp_time。按照tmp_time大小进行循环,把次数大于0的都依次输出,输出一次都要减1。这样就可以将全部字符按照所需的要求输出。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值