天天看點

LeetCode -28.實作strStr() -簡單

一、題目描述

LeetCode -28.實作strStr() -簡單

示例:

LeetCode -28.實作strStr() -簡單

說明:

LeetCode -28.實作strStr() -簡單

三、解題思路

從haystack的第0個碼點往後推移,利用String的substring方法截取和needle長度相同的字元串,用以比較。比較簡單。

需要注意的是substring的用法,這是一個完整的單詞,是以第二個s不用根據駝峰命名法大寫,這個不要搞錯。還有substring(a,b)取前閉後開,[a,b)

四、自寫代碼

class Solution {
    public int strStr(String haystack, String needle) {
        int length = needle.length();
        if (length == 0)
            return 0;
        
        for(int i = 0; i <= haystack.length() - length; i++){
            if(haystack.substring(i,i+length).equals(needle))
                return i;
        }

        return -1;
    }
}