王廷瑋|數位醫療|智慧醫療: 28. Find the Index of the First Occurrence in a String WFU

2024年7月3日 星期三

28. Find the Index of the First Occurrence in a String

28. Find the Index of the First Occurrence in a String


給定兩個字符串 needle 和 haystack,返回 needle 在 haystack 中首次出現的索引,如果 needle 不是 haystack 的一部分,則返回 -1。

範例 1:

輸入:haystack = "sadbutsad", needle = "sad" 輸出:0 解釋:"sad" 在索引 0 和 6 處出現。首次出現是在索引 0,因此我們返回 0。


Python


class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if not needle:
return 0
# Get the lengths of haystack and needle
len_h = len(haystack)
len_n = len(needle)
# Loop through haystack to find the needle
for i in range(len_h - len_n + 1):
if haystack[i:i + len_n] == needle:
return i
return -1

16.48MB, 41ms


C++


#include <string>

using namespace std;

class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.empty()) {
return 0;
}
// Get the lengths of haystack and needle
int len_h = haystack.size();
int len_n = needle.size();
// Loop through haystack to find the needle
for (int i = 0; i <= len_h - len_n; ++i) {
if (haystack.substr(i, len_n) == needle) {
return i;
}
}
return -1;
}
};

7.98MB, 0ms


Javascript


/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function(haystack, needle) {
if (needle === "") {
return 0;
}
// Get the lengths of haystack and needle
const len_h = haystack.length;
const len_n = needle.length;
// Loop through haystack to find the needle
for (let i = 0; i <= len_h - len_n; i++) {
if (haystack.substring(i, i + len_n) === needle) {
return i;
}
}
return -1;
};

48.72MB, 47ms