搜狐笔试两道算法题

1 排序数字字符串的数字(升序),遇到0时从数字字符串中删除,如"1324"排序后输出"1234","9002"排序后应该为"29"

#include<iostream>
#include<string>
using namespace std;

int cmp(const void* a,const void* b)
{
	return *(char *)a-*(char*)b;
}

void reverseAndOutput(char* str)
{
	if(str==NULL) return;

	char* preIndex = str;
	char* postIndex = str;

	while(*preIndex!='0'&&*preIndex!='\0')
		preIndex++;
	postIndex = preIndex;

	while(*postIndex!='\0')
	{
		if(*postIndex!='0')
			*preIndex++ = *postIndex;
		postIndex++;
	}
	*preIndex = '\0';
	qsort(str,preIndex-str,sizeof(char),cmp);
	cout<<str<<endl;
}


int main()
{
	char str[] = "01000007009020000500000300040";
	reverseAndOutput(str);
}


2 前后点到输入的英文中的单词位置,标点符号(只可以出现在句尾)位置不变,如输入"Hello how are you",输出应该为"you are how Hello!"。

#include<iostream>
#include<string>
using namespace std;

void reverse(char* head,char* tail)
{
	if(head==NULL||tail==NULL)
		return;

	while(head<tail)
	{
		char temp = *head;
		*head = *tail;
		*tail = temp;
		head++;
		tail--;
	}
}

void reverseAndOutput(char* str)
{
	char* preIndex = str;
	char* postIndex = str;

	while((*postIndex<='z'&&*postIndex>='a')
		||(*postIndex<='Z'&&*postIndex>='A')
		||*postIndex==' ') postIndex++;
	postIndex--;

	reverse(preIndex,postIndex);

	char* end = postIndex+1;
	preIndex = postIndex = str;


	while(preIndex!=end)
	{
		if(*preIndex==' ')
		{
			preIndex++;
			postIndex++;
		}
		else if(*postIndex==' '||postIndex==end)
		{
			reverse(preIndex,postIndex-1);
			preIndex=postIndex;
		}
		else
			postIndex++;

	}
	cout<<str<<endl;
}


int main()
{
	char str[] = "Hello my class mates!???";
	reverseAndOutput(str);
}


 

你可能感兴趣的:(算法,null,Class)