把字符串中*全部移到字符串的头部---要求时间复杂度和空间复杂度

来源:互联网 发布:安卓中电量优化怎么做 编辑:程序博客网 时间:2024/06/02 04:15
#include <stdio.h>//把字符串中*全部移到字符串的头部void moveCharToHead(char *str){if(str == NULL)return ;char *pString = str;char *tmp = NULL;while(*pString != '\0'){if(*pString == '*'){tmp = pString;while(tmp > str){*tmp = *(tmp - 1);tmp --;}*tmp = '*';str ++;}pString ++;}}int main(){char str[] = "*th*an*k* yo*u *v*er*y* m**uc*h !";int len =  sizeof(str) / sizeof(char);moveCharToHead(str);printf("%s\n",str);}


数组中,数值移动问题.

如下:

int A[nSize],其中隐藏着若干0,其余非0整数,写一个函数int Func(int* A, int nSize),使A把0移至后面,非0整数移至 
数组前面并保持有序,返回值为原数据中第一个元素为0的下标。(尽可能不使用辅助空间且考虑效率及异常问题,注释规范且给出设计思路)

#include <stdio.h>int Func(int* A, int nSize)  {    int tag = 0,nCount = 0;   int *p = NULL,*tmp = NULL;   if((A == NULL) || (nSize <= 0))   {    return -1;   }   while(nCount <  nSize)   {    if(A[ nCount ] == 0)    {     tag = 1;     break;    }    else    {     nCount ++;    }   }   if(tag == 1)   {    p = A + nCount;    while(p < A + nSize)    {     if(*p == 0)     {      tmp = p;      tag = *p;      while(tmp < A + nSize)      {       *tmp = *(tmp + 1);       tmp ++;      }      nSize --;      *(A + nSize) = tag;     }     else     {      p ++;     }       }    return nCount;   }   else   {    printf("Donnot find the zero.\n");    return -1;   }   }  int main(){int A[] = {0,8,0,7,6,5,0,3,2,0,1,0,8,0,9};int i,len = sizeof(A) / sizeof(int);Func(A,len);for(i = 0;i < len;i ++){printf("%3d",A[i]);}printf("\n");}


好的算法:

void DeleteChars(char* pStrSource, const char* pStrDelete)  {          if(NULL == pStrSource || NULL == pStrDelete)               return;          const unsigned int nTableSize = 256;          int hashTable[nTableSize];          memset(hashTable, 0, sizeof(hashTable));         const char* pTemp = pStrDelete;          while ('\0' != *pTemp)          {                hashTable[*pTemp] = 1;               ++ pTemp;          }        char* pSlow = pStrSource;          char* pFast = pStrSource;         while ('\0' != *pFast)          {                  if(1 != hashTable[*pFast])               {                      *pSlow = *pFast;                      ++ pSlow;                }                ++pFast;          }          *pSlow = '\0';   } 


 

原创粉丝点击