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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zzb2019/article/details/82389154

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

字符串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;
}

猜你喜欢

转载自blog.csdn.net/zzb2019/article/details/82389154
今日推荐