如果模式是 abba 并且将给出一个与模式匹配的 "redbluebluered" 字符串,如何匹配模式

how to match the pattern if the pattern is abba and there will be given a single string that is "redbluebluered" which matches the pattern

我昨天在校园驱动器的技术回合中,要求解决这个问题。我没有接近这个问题的解决方案,我被拒绝了,现在我仍在尝试解决这个问题,但无法解决 solve.I 我想知道如何解决这个问题 problem.The 面试官说测试字符串中不会有 space 并且它是单个字符串。

如果有输入String pattern will abba。 那么匹配模式将是 1) 猫狗猫 2) 红蓝蓝红 3) noyesyesno

不匹配的模式将是 1) 猫狗猫 2) 红蓝红 3) 是的

(抱歉我的英语不好)

谢谢。

如果您需要不使用特定词的通用解决方案,这可能就是您所追求的:

(\w+)(\w+)

https://regex101.com/r/hP8lA3/1

它的效率不是很高,但它会尝试贪婪地匹配两个词组,然后使用 backreferences 确保它们之后是第二组,然后是第一组。

你可以让它更通用来匹配两组 any 字符(除了换行符):(.+)(.+)

这是使用 C# 解决整个问题的一种可能方法:

private bool matcher(string pseudoPattern, string text) {
    string regexPattern = "^";
    var uniqueParts = new List<char>();

    foreach (char part in pseudoPattern.ToCharArray())
        if (uniqueParts.Contains(part)) {
            int backReference = uniqueParts.FindIndex(p => p == part) + 1;

            regexPattern += @"\" + backReference;
        }
        else {
            uniqueParts.Add(part);

            regexPattern += @"(\w+)";
        }

    regexPattern += "$";

    var regex = new Regex(regexPattern);

    return regex.Match(text).Success;
}