当前位置: 面试刷题>> 找出字符串中第一个匹配项的下标(经典算法150题)


完整题目描述

题目

在给定一个字符串s和一个子串t的情况下,请编写一个函数来找出子串t在字符串s中第一次出现的位置(下标)。如果子串t不在字符串s中,则返回-1。注意,字符串的索引从0开始。

示例

  • 输入:s = "hello world", t = "world"

  • 输出:6

  • 输入:s = "hello", t = "hello world"

  • 输出:-1

PHP 代码示例

function findFirstOccurrence($s, $t) {
    $lengthS = strlen($s);
    $lengthT = strlen($t);
    
    if ($lengthT === 0) {
        return 0; // 如果子串为空,则默认返回0,因为空字符串可以在任何位置“匹配”
    }
    
    for ($i = 0; $i <= $lengthS - $lengthT; $i++) {
        $match = true;
        for ($j = 0; $j < $lengthT; $j++) {
            if ($s[$i + $j] !== $t[$j]) {
                $match = false;
                break;
            }
        }
        if ($match) {
            return $i;
        }
    }
    
    return -1; // 没有找到匹配项
}

// 示例用法
$s = "hello world";
$t = "world";
echo findFirstOccurrence($s, $t); // 输出: 6

Python 代码示例

def find_first_occurrence(s, t):
    if not t:
        return 0  # 空字符串默认返回0
    for i in range(len(s) - len(t) + 1):
        if s[i:i+len(t)] == t:
            return i
    return -1  # 没有找到匹配项

# 示例用法
s = "hello world"
t = "world"
print(find_first_occurrence(s, t))  # 输出: 6

JavaScript 代码示例

function findFirstOccurrence(s, t) {
    if (t.length === 0) {
        return 0; // 空字符串默认返回0
    }
    for (let i = 0; i <= s.length - t.length; i++) {
        if (s.substring(i, i + t.length) === t) {
            return i;
        }
    }
    return -1; // 没有找到匹配项
}

// 示例用法
let s = "hello world";
let t = "world";
console.log(findFirstOccurrence(s, t)); // 输出: 6

以上代码示例均实现了查找字符串中第一个匹配项下标的功能,并在未找到匹配项时返回-1。这些代码示例简洁明了,适用于各种编程语言的面试场景。

推荐面试题