-1

我正在寻找以下字符串模式匹配问题的解决方案。

你有一个接受两个参数的函数:模式和输入——两者都是字符串。

让我们说pattern: aabbaainput: catcatdogdogcatcat

这些特定参数将被视为匹配,因为 的字符中有一个模式input,并且该模式与 中的单词模式匹配pattern

返回 aboolean以指示匹配的位置。上面给出的示例将返回1.

function (pattern, input) {
  // patterns within the input string are elucidated from input
  // those patterns are checked against the pattern
  return boolean
}
4

3 回答 3

3

广义问题“查找给定字符串的模式”更难解决,因为一个字符串可以符合多个模式。例如,

catcatdogcat

符合许多模式。这是一个非详尽的列表:

aaba           cat cat dog cat
a              catcatdogcat
ab             catcat dogcat
abcabcefgabc   c a t c a t d o g c a t
ababcab        ca t ca t dog ca t

所以我不认为“找到所有模式,然后看看提议的模式是否在其中”的方法会奏效。

这意味着我们可能希望使用建议的模式作为指导来尝试分解字符串,但我也不完全确定它会是什么样子。

在特定情况下,当模式以相同的子字符串开头和结尾(例如 in aaba)时,我想您可以从字符串的开头和结尾开始,一次使用一个字符,直到获得匹配:

catcatdogcat
CatcatdogcaT
CAtcatdogcAT
CATcatdogCAT <-- Substring "CAT" is a candidate for "a". Check if that pattern matches.

但更一般的情况又更难了。但是,可以采取类似的方法,例如尝试每个字符串以查看它是否符合模式,并进行回溯:

catcatdogcat
Catcatdogcat <-- The string isn't "CCsomethingC", so a != "C"
CAtcatdogcat <-- the string isn't "CACAsomethingCA", so a != "CA"
CATcatdogcat <-- the string is "CATCATsomethingCAT", so a = "CAT" is a candidate.

找到候选对象后,您可以将其从字符串和模式字符串中删除,从而减少与dog模式进行比较的下一步b。在伪代码中,

checkpattern(pattern, string) :=
  if (pattern has just one letter) 
    return true
  if (pattern has more than one letter, but it's one character repeated)
    return whether the string repeats that way
  for (each substring from the start of the string of length x=[0..])
    does the string match this candidate substring following the pattern?
    if (yes)
      if (checkpattern(pattern - letter, string - substring))
        return true
      else
        continue
    if (no)
      continue
  return false

我认为那会奏效。显然这个伪代码有很多细节,而且效率不高,但它可以完成工作。

于 2018-01-15T14:57:04.383 回答
0

创建一个嵌套循环进行检查。

int i =0;
char tester [] = "xyzfffasdfsadf";
bool checker = false;
while (tester[i] != '\0')
{
    if (tester [i] == 'x')
    {
        i++;
       if (tester[i] == 'y')
       {
          i++;
          if (tester[i] == 'z')
          {
             checker = true;
          }
       }
   }else {
    i++;
   }
}
if(checker == true){
cout << "Pattern exist";
}

这是c ++或java中的一种简单方法,我会这么认为。嵌套循环的数量将是要检查模式是否存在的字符数。您还可以在最后一个循环中包含第二个计数器,以递增以计算模式发生的次数。

于 2018-01-13T02:25:38.583 回答
0

这是我是怎么做到的

def check_pattern(s1,s2):
    i=j=97
    p1=p2=""

    for index1,l1 in enumerate(s1):
        if l1 not in s1[0:index1]:
            p1+=chr(i)
            i+=1
        else:
            p1+= chr(97+s1.index(l1))

    
    for index2,l2 in enumerate(s2):
        if l2 not in s2[0:index2]:
            p2+=chr(j)
            j+=1
        else:
            p2+= chr(97+s2.index(l2))

    if p1==p2:
        return True
    else:
        return False

z=check_pattern("aab","xxz")
print(z)
于 2021-06-18T05:12:43.583 回答