字符串的全排列

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_STR 10000


void
makeEmpty(char** strset)
{
  memset(strset, 0, MAX_STR*sizeof(char*));
}

void
insert_t(char* str_p, char insert, char* str_alloc, int index)
{
  int len = strlen(str_p);
  strncpy(str_alloc, str_p, len);
  int nbytes = (len - index)*sizeof(char);
  char* src = str_alloc + index*sizeof(char);
  char* dest = str_alloc + (index+1)*sizeof(char);
  memmove(dest, src, nbytes);
  str_alloc[index]=insert;
  str_alloc[len+1]='\0';
}

void
insertIntoStrSet(char** strset, int* element, char insert)
{
  int i = 0;
  int tableNum = *element;
  for(;i<tableNum;++i){
    int strlen_t = strlen(strset[i]);//求得已存在字符串长度
    int j;
    for(j =0; j< (strlen_t+1); ++j){
      char* temp = (char*)malloc(sizeof(char)*(strlen_t+2));
      insert_t(strset[i], insert, temp, j);
      strset[*element+j]=temp;//复制指针
    }
    *element = *element+strlen_t+1;
  }
}

int
main()
{
  char* orstr = "abcdef";
  char** strset = (char**)malloc(sizeof(char*)*MAX_STR);
  int element = 0;
  makeEmpty(strset);
  int orlen = strlen(orstr); //获得原始字符串长度
  int i = 0;
  char insert = orstr[i];
  strset[0] = (char*)malloc(sizeof(char)*(orlen+1));//分配成原始字符串长度+1
  strncpy(strset[0], &insert, 1);
  strset[0][1]='\0';
  ++element;//先将原始字符串的首字符插入
  for(i=1; i< orlen; ++i){
    insert = orstr[i];//需要插入的字符
    insertIntoStrSet(strset, &element, insert);
  }
  int n = 0;
  for(;n < element; ++n){//检测结果
    printf("%s\n", strset[n]);
  }
}

posted @ 2011-04-28 14:20  Richard Zhong  阅读(971)  评论(0编辑  收藏  举报