近期公司笔试编程题(2)

给定一个字符串,每次从头部或者尾部取较小子串的首字母,

字符串ABCD从头部看,子串为ABCD,从尾部看,子串为DCBA.

例如给定字符串:ABCBCB ,输出为:ABCBCD

过程为:
    ACDCB=>(CDBCB,A)=>(CDBC,AB)=>(CDB,ABC)=>(CD,ABCB)=>(D,ABCBC)=>ABCBCD 

代码为:

#include<iostream>
using namespace std;
#include<stdio.h>
char *GetMinStr(char *str)
{
	int n = strlen(str);
	char *result = (char*)malloc(n + 1);
	memset(result, 0, n);
	*(result + n + 1) = '\0';
	int j = 0;
	for (int i = 0; i < n; ++i)
	{
		if (str[i] < str[n - 1])//如果第一个字符比最后一个字符小 (ASCII码),则把第一个放入result
		{
			result[j++] = str[i];
		}
		else if (str[i] > str[n - 1])//如果第一个字符比最后一个字符大 (ASCII码),则把最后一个放入result
		{
			result[j++] = str[n - 1];
			i--;
			n--;
		}
		else//如果相等就比较前面的后一个,和后面的前一个
		{
			if (str[i + 1] < str[n - 2])//如果前面的小
			{
				result[j++] = str[i];
			}
			else if (str[i + 1] > str[n - 2])//如果后面的小
			{
				result[j++] = str[n - 1];
				i--;
				n--;
			}
		}
	}
	return result;
}

int main()
{
	char str[] = "ACDBCB";
	cout << str << endl;
	char *result = GetMinStr(str);
	cout << result << endl;
	system("pause");
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值