Follow

Follow

·May 8, 2022·

# 28. Implement strStr()

## 題目敘述

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

``````Input: haystack = "hello", needle = "ll"
Output: 2
``````

Example 2:

``````Input: haystack = "aaaaa", needle = "bba"
Output: -1
``````

Clarification:

What should we return when `needle` is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when `needle` is an empty string. This is consistent to C's `strstr()` and Java's `indexOf()`.

Constraints:

• `haystack` and `needle` consist only of lowercase English characters.

## 解法解析

### 解法範例

#### Go

``````func strStr(haystack string, needle string) int {
if haystack == needle {
return 0
}
for i := 0; i <= len(haystack)-len(needle); i++ {
if haystack[i:i+len(needle)] == needle {
return i
}
}

return -1
}
``````

#### JavaScript

``````/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function (haystack, needle) {
if (needle.length === 0) return 0;
return haystack.indexOf(needle);
};
``````

#### Kotlin

``````class Solution {
fun strStr(haystack: String, needle: String): Int {
if (needle.isEmpty()) return 0
return haystack.indexOf(needle)
}
}
``````

#### PHP

``````class Solution
{

/**
* @param String \$haystack
* @param String \$needle
* @return Integer
*/
function strStr(\$haystack, \$needle)
{
return strpos(\$haystack, \$needle) !== false ? strpos(\$haystack, \$needle) : -1;
}
}
``````

#### Python

``````class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if needle in haystack:
return haystack.index(needle)
return -1
``````

#### Rust

``````
``````

#### Swift

``````class Solution {
func strStr(_ haystack: String, _ needle: String) -> Int {
guard !needle.isEmpty else { return 0 }
guard haystack.count >= needle.count else { return -1 }

let distance = haystack.count - needle.count
for i in 0...distance {
let start = haystack.index(haystack.startIndex, offsetBy: i)
let end = haystack.index(haystack.startIndex, offsetBy: i+needle.count)

if haystack[start..<end] == needle {
return start.encodedOffset
}
}
return -1
}
}
``````