当前位置:网站首页>Leetcode3. Implement strstr()

Leetcode3. Implement strstr()

2022-07-06 01:38:00 East invincible is me

Realization  strStr()  function .

Here are two strings  haystack and needle , Please come in haystack Find in string needle The first place the string appears ( Subscript from 0 Start ). If it doesn't exist , Then return to   -1 .

explain :

When  needle  When it's an empty string , What value should we return ? This is a good question in an interview .

For this question , When  needle  When it's an empty string, we should return 0 . This is related to C Linguistic  strstr()  as well as Java Of  indexOf()  The definition matches .

Example 1:

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

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

Tips :

1 <= haystack.length, needle.length <= 104
haystack and needle It only consists of lowercase English characters

Personal answers

Method 1 :

def strStr(str1,str2):
    return str1.find(str2)
str1="hello"
str2="ll"
print(strStr(str1,str2))
This solution uses functions built into strings , Too opportunistic .
 

Method 2 :
class Solution:
    
    def strStr(self,str1,str2):
        i=0
        while(i<len(str1)):
            if((str1[i:i+len(str2)])==str2):
                return i
            else:
                i=i+1        
        else:
            return -1

My own way of thinking , Slice method .( It's the idea of palindrome string before , thus it can be seen , Even if the question is finished , We must also review, It's good for doing problems in the future .)

  Official answer

you 're right , I use violent matching , but KMP What is it? ?

 

原网站

版权声明
本文为[East invincible is me]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060136260784.html