当前位置: 面试刷题>> 字模式 (经典算法题500道)


虽然原题目描述不完整,但基于常见的算法题类型和面试中可能遇到的题目,我假设这是一个关于字符串处理或模式匹配的题目。题目可能是要求你实现一个函数,该函数能够检测一个字符串中是否包含特定的“字模式”(比如特定的子字符串或满足某种条件的序列)。

假设题目描述

题目描述: 实现一个函数 containsPattern(str, pattern),该函数接受两个字符串参数 strpatternpattern 是一个简化的模式字符串,其中 "*" 可以代表任意字符(包括空字符),而其它字符则必须严格匹配。函数需要返回布尔值,表示 str 是否包含符合 pattern 描述的子串。

示例

  • containsPattern("abcxyz", "a*z") 应返回 true,因为 "a*z" 中的 "*" 可以匹配 "bcx"
  • containsPattern("abcde", "b*d") 应返回 true,因为 "*" 可以匹配 "c"
  • containsPattern("abcde", "b*e") 应返回 true,因为 "*" 可以匹配 "cde"
  • containsPattern("abcde", "f*g") 应返回 false,因为没有子串符合 "f*g" 的模式。

PHP 代码示例

function containsPattern($str, $pattern) {
    $len = strlen($pattern);
    $i = 0;
    while ($i < strlen($str)) {
        $j = 0;
        while ($j < $len && ($pattern[$j] == '*' || $pattern[$j] == $str[$i + $j])) {
            $j++;
        }
        if ($j == $len) {
            return true; // 完全匹配模式
        }
        if ($pattern[$j] == '*' && $j > 0) {
            $i++; // 跳过 '*' 前的字符,重新尝试匹配
        } else {
            $i += $j > 0 ? 1 : 0; // 如果没有 '*' 或 '*' 在末尾,则向前移动
        }
    }
    return false;
}

// 测试
echo containsPattern("abcxyz", "a*z") ? "true" : "false"; // true
echo containsPattern("abcde", "b*d") ? "true" : "false"; // true
echo containsPattern("abcde", "b*e") ? "true" : "false"; // true
echo containsPattern("abcde", "f*g") ? "true" : "false"; // false

Python 代码示例

def containsPattern(str, pattern):
    i = 0
    while i < len(str):
        j = 0
        while j < len(pattern) and (pattern[j] == '*' or pattern[j] == str[i + j]):
            j += 1
        if j == len(pattern):
            return True
        if pattern[j] == '*' and j > 0:
            i += 1
        else:
            i += j > 0
    return False

# 测试
print(containsPattern("abcxyz", "a*z"))  # True
print(containsPattern("abcde", "b*d"))  # True
print(containsPattern("abcde", "b*e"))  # True
print(containsPattern("abcde", "f*g"))  # False

JavaScript 代码示例

function containsPattern(str, pattern) {
    let i = 0;
    while (i < str.length) {
        let j = 0;
        while (j < pattern.length && (pattern[j] === '*' || pattern[j] === str[i + j])) {
            j++;
        }
        if (j === pattern.length) {
            return true;
        }
        if (pattern[j] === '*' && j > 0) {
            i++;
        } else {
            i += j > 0 ? 1 : 0;
        }
    }
    return false;
}

// 测试
console.log(containsPattern("abcxyz", "a*z")); // true
console.log(containsPattern("abcde", "b*d")); // true
console.log(containsPattern("abcde", "b*e")); // true
console.log(containsPattern("abcde", "f*g")); // false

这些代码示例展示了如何实现一个简单的字符串模式匹配函数,根据题目要求,它们能够判断一个字符串中是否包含符合特定模式的子串。

推荐面试题