LeetCode Python, Java, C++ > 28. 找出字符串中第一个匹配项的下标 > 已支持 Python, JavaScript, Ruby, C++, Java, Go, C# > GitHub
力扣链接:28. 找出字符串中第一个匹配项的下标,难度等级:简单。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。
示例 1:
输入: haystack = "sadbutsad", needle = "sad"
输出: 0
解释: "sad" 在下标 0 和 6 处匹配。 第一个匹配项的下标是 0 ,所以返回 0 。
示例 2:
输入: haystack = "leetcode", needle = "leeto"
输出: -1
解释: "leeto" 没有在 "leetcode" 中出现,所以返回 -1 。
约束:
1 <= haystack.length, needle.length <= 10^4haystack和needle仅由小写英文字符组成
相关标签
思路
- 这样的题目,如果用内置的
index(),一行代码就可以实现。显然,出题人是想考察我们对循环的控制能力。 针对
heystack,依次遍历每个字符。如果从当前字符开始到needle长度的子串与needle相同,则返回当前字符的位置。本题直接看代码比较容易理解。
👋 站长寄语:我还为你开发了 coder.id - 打造程序员个人IP, 包含作品集、简历和博客等,助您顺利拿到 Offer!
复杂度
时间复杂度
O(N * M)
空间复杂度
O(1)
Python #
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
n = len(haystack)
m = len(needle)
for i in range(n - m + 1):
if haystack[i:i + m] == needle:
return i
return -1
JavaScript #
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function(haystack, needle) {
const n = haystack.length;
const m = needle.length;
for (let i = 0; i <= n - m; i++) {
if (haystack.substring(i, i + m) === needle) {
return i;
}
}
return -1;
};
Ruby #
# @param {String} haystack
# @param {String} needle
# @return {Integer}
def str_str(haystack, needle)
(0..haystack.size - needle.size).each do |i|
if haystack[i...i + needle.size] == needle
return i
end
end
-1
end
C++ #
class Solution {
public:
int strStr(string haystack, string needle) {
for (int i = 0; i < haystack.length(); i++) {
int j = 0;
while (i + j < haystack.length() && haystack[i + j] == needle[j]) {
j++;
if (j == needle.length()) {
return i;
}
}
}
return -1;
}
};
Java #
class Solution {
public int strStr(String haystack, String needle) {
for (int i = 0; i < haystack.length(); i++) {
int j = 0;
while (i + j < haystack.length() && haystack.charAt(i + j) == needle.charAt(j)) {
j++;
if (j == needle.length()) {
return i;
}
}
}
return -1;
}
}
Go #
func strStr(haystack string, needle string) int {
for i := 0; i < len(haystack); i++ {
j := 0
for i+j < len(haystack) && haystack[i+j] == needle[j] {
j++
if j == len(needle) {
return i
}
}
}
return -1
}
C# #
public class Solution {
public int StrStr(string haystack, string needle) {
for (int i = 0; i < haystack.Length; i++) {
int j = 0;
while (i + j < haystack.Length && haystack[i + j] == needle[j]) {
j++;
if (j == needle.Length) {
return i;
}
}
}
return -1;
}
}
其它语言
欢迎贡献代码到 GitHub repo -> 28. 找出字符串中第一个匹配项的下标。感谢!打造你的开发者个人IP
- 📄 简历 + 作品集 + 博客
- 🌐 支持绑定自定义域名
- ✨ 顶级子域名:
https://yourname.coder.id