C++笔试面试(算法题集三)

1>    编写strcpy函数,已知函数原型char*strcpy(char* strDest,char* strSrc)

ANSWER:

Chat* strcpy(char* strDest,char* strSrc)

{

If(strSrc==NULL)  return NULL;

Char*ch1=strSrc,*ch2=strDest;

While(*ch1!=’\0’)

{

    *ch2++=*ch1++;

}

*ch2=’\0’;

Return strDest;

}

 

2>    用递归的方法判断整数组a[N]是不是升序排序

ANSWER:

Boolean isAscending(int a[])

{

    ReturnisAscending(a,0);

}

Bool isAscending(int a[],int start)

{

    Returnstart==length-1 ||isAscending(a,start+1);

}

 

3>    删除字符串中的数字并压缩字符串

Char * partition(const char *str)

{

Char* i=str;

Char* j=str;

While(*i!=’\0’)

{

    If(*i>’9’ || *i<’0’)

        *j++=*i++;

    Else

         *i++;

}

*j=’\0’;

Return str;

}

 

4>    函数将字符串的字符’*’移到字符串的前部,前面的非’*’字符移到字符串的后面部分。

ANSWER:

 

Int partitionStr(char a[])

{

Int count=0;

Inti=a.length-1,j=a..length-1;

While(i>=0)

{

    If(a[i]!=’*’)

    {

        Swap(a,i--,j--)

}

Else

{

    i--;

    count++;

}

}

Return count;

}

 

5>    已知一个字符串,寻找字符串sub在原字符串中出现的次数。

ANSWER:

Int count_of_substr(chat *str,char *sub)

{

Int n=strlen(sub);

Int count=0;

Char *p=stt;

While(p!=’\0’)

{

    If(strcmp(p,sub,n))

        Count++;

    P++;

}

Return count;

}

 

6>    一个最小堆,也是完全二叉树,用按层遍历数组表示。

1, 求节点a[n]的子节点的访问方式

2, 插入一个节点的程序void add_element(int *a,int size,int val);

3, 删除最小节点的程序

ANWSER:

Void add_element(int *a,int size,int val)

{

A[size]=val;

Int p=size/2-1;

Int c=size;

While(p>=0)

{

    If(a[p]

        Break;

    Else

    {

        A[c]=a[p];

        C=p;

        P=(p-1)/2;

}

}

A[c]=val;

}

 

Void Del(int *a,int size)

{

A[0]=a[size-1];

Int val=a[0];

Size--;

Int p=0;

Int c=2*p+1;

While(c<=size-1)

{

    If(ca[c+1])

        C++;

    If(a[p]<=a[c])

        Break;

    Else

    {

        A[p]=a[c];

        P=c; c=2*p+1;

}

}

A[p]=val;

}

 

7>    字符串的组合

ANWSER:

Void Combination_m(chat *pStr,intm,vector &result)

{

If(pStr==NULL||(*pStr==’\0’ &&m!=0))

    Return ;

If(m==0)

    Cout<

 

Result.push_back(*pStr);

Combination_m(pStr+1,m-1,result);

Result.pop_back();

Combination_m(pStr+1,m,result);

}

 

Void Combination(char *pStr)

{

If(pStr==NULL||*pStr==’\0’)

    Return ;

Intlen=strlen(str);

For(inti=1;i<=len;i++)

{

    Vector result;

    Combination_m(pStr,I,resulr);

}

}

你可能感兴趣的:(Interview,Union)