Leetcode 28 Implement strStr()

HowieLee59發表於2018-10-25

Implement strStr().

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

Example 1:

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

Example 2:

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

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

1)

class Solution {
    public int strStr(String haystack, String needle) {
        if(haystack.length() == 0 && needle.length() == 0){
            return 0;
        }else if(haystack == null || haystack.length() == 0){
            return -1;
        }
        int index = haystack.indexOf(needle);
        if(index > -1){
            return index;
        }else{
            return -1;
        }
    }
}

2)

class Solution {
    public int strStr(String haystack, String needle) {
        return (needle.isEmpty() || haystack.indexOf(needle) == 0) ? 0 : haystack.indexOf(needle);
    }
}

可以直接使用庫函式或者是自己手動的進行匹配。

相關文章