Leetcode 28. Find the Index of the First Occurrence in a String

Find the Index of the First Occurrence in a String

Find the Index of the First Occurrence in a String :

給定兩個字串(haystack,needle),檢查needle是否在haystack內,若有回傳needle第一次出現時的index,若無則回傳-1,若needle為空,回傳0

Python

方法一 : 比對haystack的範圍內是否包含needle,一個一個數比對

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        m,n= len(haystack),len(needle)
        for i in range(m-n+1):
            if haystack[i:i+n]==needle:    #一個一個數比對
                return i
        return -1

方法二 : find函數

python內建尋找函數

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        return haystack.find(needle)

C++

迴圈比對haystack跟needle,如果haystack的substr跟needle相等的話,回傳當前的位置i,否則回傳-1

var strStr = function(haystack, needle) {
    if(!needle) return 0;
    if(!haystack || needle.length > haystack.length) return -1;

    var i,j;
    for(i = 0 ; i < haystack.length ; i++){
       var str = haystack.substr(i,needle.length);
       if(str == needle){
           return i;
       }
    }

    return -1;
};

呼叫API,indexOf(x)就可以直接得到答案

var strStr = function(haystack, needle) {
    return haystack.indexOf(needle);
}