algorithm - 在字符串缓冲区/段落/文本中查找单词

标签 algorithm amazon

这是在亚马逊电话采访中被问到的——“你能写一个程序(用你喜欢的语言 C/C++/等)在一个大的字符串缓冲区中找到一个给定的词吗?即数字出现次数“

我仍在寻找我应该给面试官的完美答案。我试着写一个线性搜索(逐个字符比较),显然我被拒绝了。

给定 40-45 分钟的电话面试时间,他/她正在寻找的完美算法是什么???

最佳答案

KMP 算法是一种流行的字符串匹配算法。

KMP Algorithm

按字符检查字符效率低下。如果字符串有 1000 个字符而关键字有 100 个字符,您不想执行不必要的比较。 KMP 算法处理许多可能发生的情况,但我想面试官正在寻找以下情况:当您开始(通过 1)时,前 99 个字符匹配,但第 100 个字符不匹配。现在,对于传递 2,您不必从字符 2 执行整个比较,而是有足够的信息来推断下一个可能的匹配可以从哪里开始。

// C program for implementation of KMP pattern searching 
// algorithm
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void computeLPSArray(char *pat, int M, int *lps);

void KMPSearch(char *pat, char *txt)
{
int M = strlen(pat);
int N = strlen(txt);

// create lps[] that will hold the longest prefix suffix
// values for pattern
int *lps = (int *)malloc(sizeof(int)*M);
int j  = 0;  // index for pat[]

// Preprocess the pattern (calculate lps[] array)
computeLPSArray(pat, M, lps);

int i = 0;  // index for txt[]
while (i < N)
{
  if (pat[j] == txt[i])
  {
    j++;
    i++;
  }

  if (j == M)
  {
    printf("Found pattern at index %d \n", i-j);
    j = lps[j-1];
  }

  // mismatch after j matches
  else if (i < N && pat[j] != txt[i])
  {
    // Do not match lps[0..lps[j-1]] characters,
    // they will match anyway
    if (j != 0)
     j = lps[j-1];
    else
     i = i+1;
  }
}
free(lps); // to avoid memory leak
}

void computeLPSArray(char *pat, int M, int *lps)
{
int len = 0;  // length of the previous longest prefix suffix
int i;

lps[0] = 0; // lps[0] is always 0
i = 1;

// the loop calculates lps[i] for i = 1 to M-1
while (i < M)
{
   if (pat[i] == pat[len])
   {
     len++;
     lps[i] = len;
     i++;
   }
   else // (pat[i] != pat[len])
   {
     if (len != 0)
     {
       // This is tricky. Consider the example 
       // AAACAAAA and i = 7.
       len = lps[len-1];

       // Also, note that we do not increment i here
     }
     else // if (len == 0)
     {
       lps[i] = 0;
       i++;
     }
   }
}
}

// Driver program to test above function
int main()
{
char *txt = "ABABDABACDABABCABAB";
char *pat = "ABABCABAB";
KMPSearch(pat, txt);
return 0;
}

这段代码取自一个非常好的教授算法的网站: Geeks for Geeks KMP

关于algorithm - 在字符串缓冲区/段落/文本中查找单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37578649/

相关文章:

algorithm - 处理大型项目的空间复杂性

python - 合并 Python 列表中的条目

algorithm - 三个顶点上有多少个无向图?

c - 匹配字符串中的子字符串,容差为 1 个字符不匹配

java - 在 ObjectListing 结果中排除前缀 S3 的 Java 客户端

java - 如何在 java 中验证 amazon s3 端点

c# - 在图像中查找图像(对象检测)

python - 列表中所有对的最小公倍数

amazon-web-services - 如何使用 Amazon Product Advertising API 搜索其他国家/地区

node.js - 亚马逊 ELB 后面带有 node-js 的远程 IP 地址