IT公司机试常考的一道题--将任意字符串逆序输出或者输出所有排列

    技术2025-02-08  24

    这道题是近几年来各大IT公司招程序员时机试很容易考的一道题,逆序输出很简单,会写程序的人都会。但是输出一段字符串的所有排序情况却不是所有人一时半会能写出来的,结合网友的代码,我整合了一下。代码如下:

    -----------------------------------------------------------------

    //逆序输出任意字符串

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

    void reverse(char *a){char p;for(int i=0;i<(int)(strlen(a)/2);i++){   p=a[i];   a[i]=a[strlen(a)-i-1];   a[strlen(a)-i-1]=p;}}

    int main(){char *a=NULL,*p=NULL;char c;int i=1;printf("请输入你的字符串:/n");p=(char *)malloc(sizeof(char *));        //使用了动态数组获取字符串p[0]='/0';while((c=getchar())!=10){   i++;   a=(char *)malloc(sizeof(char *)*(i));   if(a==NULL)    printf("Memory Error!");   for(int j=0;j<i-1;j++)    a[j]=p[j];   a[j-1]=c;   a[j]='/0';   p=a;}reverse(a);/*另外一种方法*/

    /*p=(char *)malloc(sizeof(char *)*2);p[0]='/0';while((c=getchar())!=10){   i++;   a=(char *)malloc(sizeof(char *)*(i));   if(a==NULL)    printf("ÄÚ´æ³ö´í!");   for(int j=1;j<i;j++)    a[j]=p[j-1];   a[0]=c;   p=a;}   */

    /*另外一种方法*/

    printf("逆序的结果为:/n");puts(a);return 0;}

    //逆序输出任意字符串

    ------------------------------------------------------------------------------

    -------------------------------------------------------------------------------

    //输出字符串的所有排列

    //方法一 使用容器vector

     

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

    vector<string> generate_permunation(string word){vector<string> result;if (word.length() == 1){   result.push_back(word);   return result;}for (unsigned int i=0;i<word.length();i++){   string shortword = word.substr(0, i) + word.substr(i+1, word.length() - i - 1);   vector<string> tmp = generate_permunation(shortword);   for (unsigned int j=0;j<tmp.size();j++)   {    result.push_back(word[i]+tmp[j]);   }}return result;}

    void print(vector<string> st){for (unsigned int i=0;i<st.size();i++){   cout<<st[i]<<endl;}}

    int main(){vector<string> test = generate_permunation("eat");print(test);return 0;}

    //方法一结束

    ---------------------------------------------------------------------------

    //方法二 使用简单的递归函数

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

    void Permutation(char a[], int start, int end){    int i,j;    char temp;    if(start == end)    {        for(i = 0; i <= end; i++)        printf(" %c ",a[i]);        printf("/n");    }       else    {        for(i = start; i <= end; i++)       {            for(j=start;j<i;j++)                if(a[j]==a[i]) goto nextI;         temp=a[start]; a[start]=a[i]; a[i]=temp;     Permutation(a, start+1, end);     temp=a[start]; a[start]=a[i]; a[i]=temp;nextI:;        }    }}

    int main(){    char A[] = "abcd";    Permutation(A,0,3);    getch();    return 0;}

    //方法二结束

    最新回复(0)