关键词和比较词的重叠

时间:2014-03-08 23:33:38

标签: c++ algorithm overlap

如何编写if语句以获得以下结果:

Keyword = face

比较词(用户输入)= effac,acer

一些例子来说明我的意思:

 Keyword: face
 Match: effac
 Overlap: 3 (fac)

 Keyword: face
 Match: acer
 Overlap: 3 (ace)

 Keyword: llama
 Match: amazing
 Overlap: 3 (ama)

 Keyword: lame
 Match: lament
 Overlap: 4 (lame)

我想我需要使用substr?或者只是一般情况下,我该怎么做才能弄清楚如何确定这两种情景的重叠?我已经准备好了函数,我只需要弄清楚我需要将哪些条件放入if / else语句,以及if / else代码块的主体。

2 个答案:

答案 0 :(得分:1)

#include <string>

std::string longestCommonSubstr( std::string& s, std::string& in) {
    size_t s_s = s.size();
    size_t in_s = in.size();
    if ( ( s_s == 0) || ( in_s == 0)) return std::string();
    size_t common_s = std::min( s_s, in_s);
    for ( size_t i = common_s; i > 0; i--) {
        size_t pos_beg = 0;
        size_t pos_end = i;
        while ( pos_end < s_s + 1) {
            std::string searched =  s.substr( pos_beg, pos_end);
            size_t found = in.find( searched);
            if ( found != std::string::npos) return searched;
            ++pos_beg;
            ++pos_end;
        }
    }
    return std::string();
}

用法:

int main(int argc, char** argv) {

    std::string me( "face");
    std::string ymey( "effac");
    std::string res = longestCommonSubstr( me, ymey); // res is "fac"
    if ( !res.empty()) {
        // found
    }
    return 0;
}

答案 1 :(得分:0)

这是一个粗略的伪代码,我认为应该可行,我假设匹配可以在开头发生或(严格地)结束。

//first case overlap is either in the beginning or the end for both words

count = 0
for i = 0 to word.length - 1
  if word[i] == match[i]
    count++
  else
    break;

if count != 0
  //output first count letters
else //you dont have your match in the beginning, check for the end
  for i = word.length - 1 to 0
    if word[i] == match[i]
      count++
    else
      break;

if count != 0
      //output last count letters

//second case overlap is at the opposite ends

for i = 0 to word.length - 1
  if word[i] == match[match.length - 1 - i]
    count++
  else
    break;

if count != 0
  //output first count letters
else //you dont have your match in the beginning, check for the end
  for i = 0 to word.length - 1 
    if word[word.length - 1 - i] == match[i]
      count++
    else
      break;

if count != 0
      //output last count letters