Implement strStr().
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.
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().
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Constraints:
func strStr(haystack string, needle string) int {
return strings.Index(haystack, needle)
}
https://go.dev/play/p/SfKM7c6aJbB
func strStr(haystack string, needle string) int {
if len(haystack) < len(needle) {
return -1
}
needler := []rune(needle)
haystacker := []rune(haystack)
for i, v := range haystacker {
if v == needler[0] {
if len(needler) == 1 {
return i
}
for j := 0; j < len(needler); j++ {
if i+len(needler) > len(haystacker) {
return -1
}
if haystacker[i+j] != needler[j] {
break
} else if j == len(needler)-1 {
return i
}
}
}
}
return -1
}
https://go.dev/play/p/4NYEN5nRbVG
func strStr(haystack string, needle string) int {
for c := range haystack {
i, j := c, 0
for i < len(haystack) && j < len(needle) {
if haystack[i] != needle[j] {
break
}
i++
j++
}
if j == len(needle) {
return c
}
}
return -1
}
func strStr(haystack string, needle string) int {
h := make(map[string]bool)
h[needle] = true
index := 0
if needle == "" {
return index
} else {
for index < len(haystack) {
if haystack[index] == needle[0] {
if len(haystack) < index + len(needle) {
return -1
}
tempS := haystack[index:(index + len(needle))]
if _, ok := h[tempS]; ok {
return index
}
}
index++
}
return -1
}
}
// 28. Implement strStr()
// time: O(n)
// space: O(1)
func strStr(haystack string, needle string) int {
k := len(needle)
if k == 0 {
return 0
}
n := len(haystack)
start := 0
for start < n {
pIdx := 0
sIdx := start
for pIdx < k && sIdx < n && haystack[sIdx] == needle[pIdx] {
sIdx++
pIdx++
}
if pIdx == k {
return start
}
start++
}
return -1
}
func strStr(haystack string, needle string) int {
if needle == "" {
return 0
}
for i := 0; i < len(haystack); i++ {
if len(needle)+i > len(haystack) {
return -1
}
if haystack[i:(len(needle)+i)] == needle {
return i
}
}
return -1
}
func strStr(haystack string, needle string) int {
res:=""
for i:=0;i<len(haystack)-len(needle)+1 && i >= 0; {
//fmt.Println("i", i, len(word))
res=haystack[i:i+len(needle)]
if res==needle{
return i
}
i++
}
return -1
}
[GO] Array and string - Two-pointer Technique - Scenario I (0) | 2022.04.09 |
---|---|
[Go] Array and string - Longest Common Prefix (0) | 2022.04.08 |
[Go] Array and string - Add binary (0) | 2022.04.03 |
[Go] Array and string - Immutable String - Problems & Solutions (0) | 2022.04.02 |
Array and string - Introduction to String from Java to Go (0) | 2022.03.30 |
댓글 영역