【问题标题】:Searching a string inside a char array using Divide and Conquer使用分治法在 char 数组中搜索字符串
【发布时间】:2015-09-03 19:19:59
【问题描述】:

假设我有一个结构数组,每个元素都有一个名称。喜欢:

struct something{
  char name[200];
}a[NMAX];

给定一个新字符串(char 数组),我需要使用分而治之的方法为其找到正确的索引。喜欢:

char choice[200];
cin>>chioce;
int k=myFunction(choice);  // will return the index, 0 otherwise
                           // of course, could be more parameters
if( k )  
 cout<<k;

我不知道如何创建那个搜索功能(我试过了,我知道 D&C 是如何工作的,但我还在学习!)。

不,我不想使用字符串!

这是我尝试过的:

int myFunction(char *choice, int l,int r)   // starting with l==0 && r==n-1
{
    int m;
    if(strcmp(a[m].name,choice)==0)
            return m;
    else{
            m=(l+r)/2;
            return myFunction(choice,l,m-1);
            return myFunction(choice,m+1,r);
    }
}

【问题讨论】:

  • 而你没有使用std::string,因为...?
  • 帮我使用字符,我还不知道字符串。
  • 你应该包括你尝试过的东西,如果人们提出改进建议,发现错误而不是提供一个工作示例,它会帮助你更多。
  • @RubenP 你越早离开char 字符串越好,它确实应该是你学习c++的第一件事。
  • 你快到了,想想“如果你找不到字符串怎么办”。提示:两个return 语句一个接一个地保证永远不会执行第二个。

标签: c++ c arrays divide-and-conquer


【解决方案1】:

这是我对您上述问题的解决方案。但是我在你的代码中修改了一些东西。

#include<iostream>
using namespace std;

#define NMAX 10

struct something{
  char *name; //replaced with char pointer so that i can save values the way i have done
}a[NMAX];

int myFunction(char *choice, int l,int r)   // starting with l==0 && r==NMAX-1
{
    if(l>r) //return if l has become greater than r
        return -1;
    int m=(l+r)/2;

    if(strcmp(a[m].name,choice)==0)
            return m+1;
    else if(l==r) //returned -1 as the value has not matched and further recursion is of no use
                return -1;
    else{

            int left= myFunction(choice,l,m-1);//replaced return
            int right= myFunction(choice,m+1,r);//by saving values returned
            if(left!=-1)                      //so that i can check them,
                return left;                  //otherwise returning from here onlywould never allow second satatement to execute
            if(right!=-1)
                return right;
            else
                return -1;
    }
}

int main(){

a[0].name="abc";
a[1].name="a";
a[2].name="abcd";
a[3].name="abcf";
a[4].name="abcg";
a[5].name="abch";
a[6].name="abcj";
a[7].name="abck";
a[8].name="abcl";
a[9].name="abcr";
char choice[200];
cin>>choice;
int k=myFunction(choice,0,NMAX-1);  // will return the index, 0 otherwise
                           // of course, could be more parameters
if( k !=-1)
 cout<<k;
 else
    cout<<"Not found";
return 0;
}

希望它会有所帮助。

【讨论】:

    猜你喜欢
    • 2014-03-26
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    • 2014-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多