leetcode -- Implemenrt strStr()

Implement strStr()code

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.ip

Example 1:leetcode

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

** Example 2: **get

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

Solutionstring

public int strStr(String hayStack, String needle){
        int hayLength = hayStack.length();
        int needleLength = needle.length();
        if (needleLength > hayLength){
            return -1;
        }

        for(int index=0; index<=hayLength-needleLength; index ++){
            if (needle.equals(hayStack.substring(index, index+needleLength))){
                return index;
            }
        }
        return -1;
    }
相關文章
相關標籤/搜索