兩道面試題

試題一:輸入i love china 輸出:china love i要求:除了定義一個數組用以存放字符串外,不得再使用其餘的數組數組

        方法一:(有一點bug)函數

#include<stdio.h>
#include<string.h>
//交換函數
char *exchange(char *ph,char *pe)
{
	while(ph<pe)
	{
		*ph^= *pe;
		*pe^=*ph;
		*ph++^=*pe--;
	}
}
//測定字符串長度函數
int fun(char *ph)
{
	int i=1;
	while(*ph!='\0')
	{
		if(*ph==' ')
			i++;
		ph++;
	}
	return i;
}

int main()
{
	char * ph,*pe,a[20];
	int i,n,k,count;
	char *p1,*p2;
	gets(a);
	n=strlen(a);
	ph=a;pe=a+n-1;
	count=fun(ph);
	exchange(ph,pe);
        //對各個子串在進行交換
	for(i = 0;i < count;i++)
	{
		k=0;
		while(*ph!=' '&&*ph!='\0')
		{
			k++;
			ph++;
		}
		p1=ph-k;
		p2=ph-1;
		exchange(p1,p2);
		ph++;
	}
	puts(a);
	return 0;
}

       方法二:code

#include <stdio.h>
#include <string.h>
#define N	30

unsigned int  swap(char *head,char *tail);
unsigned int getdata(char * dest);

int main()
{
	int count = 0;
	char str[N + 1] = {0};
	char *head = str,
		 *tail = str;
	swap(str,str + getdata(str) - 1);//先總體交換
//從開始一個一個子串的進行交換
	while(*tail != '\0' && *head != '\0')
	{
		while(*head == ' ' && *head != '\0')
			head ++;
		tail = head;
		while(*tail != ' ' && *tail != '\0')
			tail ++;
		count = swap(head,tail - 1);
		head = tail;
	}
	printf("count = %d\n",count);
	puts(str);
	return 0;
}
//輸入字符串函數
unsigned int getdata(char * dest)
{
	char ch;
	int count = 0;
	char *old = dest;
	if(dest == NULL)
		return 0;
	while('\n' != (ch = getchar()) &&  count < N )
		*dest ++ = ch,count ++;
	*dest = '\0';
	return dest - old;
}
//交換函數
unsigned int swap(char * head,char *tail)
{
	static int i = 0;
	if(head == NULL || tail == NULL)
		return 0;
	while(head < tail)
	{
		*head ^= *tail;
		*tail ^= *head;
		*head ++ ^= * tail -- ;
	}
	return ++ i;
}

試題二:輸入:一個字符串由數字子串和字母子串組成(不區分大小寫)輸出:其最大子串的長度字符串

 

#include<stdio.h>
#define N 40
int sub_srting(char *ph)
{
	int m,k=0,i,b[N]={0};
	char *pe=ph;
	while(*pe!='\0')
	{
		while((*pe>='0'&&*pe<='9')&&*pe!='\0')
			pe++;
		b[k++]=pe-ph;
		ph=pe;
		while((*pe>='a'&&*pe<='z'||*pe>='A'&&*pe<='Z')&&*pe!='\0')
			pe++;
		b[k++]=pe-ph;
		ph=pe;
	}

	for(i=0;i<=k-2;i++)
		if(b[i]>b[i+1])
		{
			b[i]^=b[i+1];
			b[i+1]^=b[i];
			b[i]^=b[i+1];
		}
	return b[i];
}

int main()
{
	char a[N];
	gets(a);
	printf("the lengest substring is %d\n",sub_srting(a));
	return 0;
}
相關文章
相關標籤/搜索