字符串匹配算法代码的建议

时间:2016-01-12 00:00:39

标签: python algorithm

调试以下问题,发布问题和代码引用我正在调试。我的问题是,如果没有必要,我认为如果条件检查,可以安全删除?如果我错了,请随时纠正我。感谢。

if len(first) > 1 and first[0] == '*' and  len(second) == 0:
    return False

给定两个字符串,其中第一个字符串可能包含通配符,第二个字符串是普通字符串。编写一个函数,如果两个字符串匹配则返回true。第一个字符串中允许使用以下通配符。

* --> Matches with 0 or more instances of any character or set of characters.
? --> Matches with any one character.

例如,g*ksgeeks匹配匹配。字符串ge?ks*geeksforgeeks匹配(请注意第一个字符串末尾的*)。但g*kgee不匹配,因为第二个字符串中不存在字符k

# Python program to match wild card characters

# The main function that checks if two given strings match.
# The first string may contain wildcard characters
def match(first, second):

    # If we reach at the end of both strings, we are done
    if len(first) == 0 and len(second) == 0:
        return True

    # Make sure that the characters after '*' are present
    # in second string. This function assumes that the first
    # string will not contain two consecutive '*'
    if len(first) > 1 and first[0] == '*' and  len(second) == 0:
        return False

    # If the first string contains '?', or current characters
    # of both strings match
    if (len(first) > 1 and first[0] == '?') or (len(first) != 0
        and len(second) !=0 and first[0] == second[0]):
        return match(first[1:],second[1:]);

    # If there is *, then there are two possibilities
    # a) We consider current character of second string
    # b) We ignore current character of second string.
    if len(first) !=0 and first[0] == '*':
        return match(first[1:],second) or match(first,second[1:])

    return False
提前谢谢, 林

1 个答案:

答案 0 :(得分:1)

if语句对函数的正常运行至关重要。删除它将带来灾难性的后果。

例如,假设first="*a"second=""。换句话说,该函数被称为match("*a","")。然后if语句将使函数返回False(这是正确的,因为a中没有second。如果没有if语句,代码将继续执行

return match(first[1:],second) or match(first,second[1:])

致电match(first[1:],second)将评估为match("a",""),并返回False。但是当代码调用match(first,second[1:])时,调用等同于match("*a",""),结果是无限递归。