November 18, 2023

Viiisit [LeetCode] - 28. Find the Index of the First Occurrence in a String

#php#javascript#ruby

keep learning, keep coding!

Problem - Find the Index of the First Occurrence in a String

Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

翻譯蒟蒻

在一個字串(haystack)中尋找另一個字串(needle)第一次出現的位置。


Solution - JavaScript

1
2
3
4
5
6
7
8
9
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function(haystack, needle) {
let index = haystack.indexOf(needle);
return index
};

Solution - Ruby

1
2
3
4
5
def str_str(haystack, needle)
index = haystack.index(needle)
# 確保在 null 的情況下回傳 -1
index.nil? ? -1 : index
end

Solution - PHP

1
2
3
4
5
6
7
8
9
function strStr($haystack, $needle) {
$index = strpos($haystack, $needle);
return $index !== false ? $index : -1;
}

$haystack = "sadbutsad";
$needle = "sad";
$result = strStrCustom($haystack, $needle);
echo $result; // 0

PHP 方法筆記

LeetCode 傳送門 - Find the Index of the First Occurrence in a String