Implement strStr

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

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().

判断needle字符串是否在haystack中,如果在,就返回下标,不在就返回-1

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

猜你喜欢

转载自blog.csdn.net/make_a_great_effort/article/details/82781957
今日推荐