strstr codesignal solution

Create a function that accepts two strings as inputs, s and x, and identifies the first occurrence of x in s. The function should return an integer representing the first occurrence of x in s and its index in s. Return -1 if there are no occurrences of x in s.

 

Solution using Go:


 

import "strings"

func strstr(s string, x string) int {
    return strings.Index(s,x)
        
   if len(s) < len(x) {
		return -1
	}
    if len(x) == 0{
        return 0
    }
    if len(s) == 0 && len(x) ==0 {
        return 0
    }
	firstIndx := -1
	for i := 0; i < len(s); i++ {
		j := 0
		if s[i] == x[j] {
			firstIndx = i
			for j = 0; j < len(x); j++ {
				if i >len(s)-1{
					firstIndx = -1
					break
				}
				if s[i] != x[j]  {
					j = 0
					i = firstIndx
					firstIndx = -1
					break
				}
				i++
			}
			if firstIndx != -1 {
				return firstIndx
			}
		}
	}
	return firstIndx
}


 

Post a Comment

0 Comments