Implement strStr()

来源:互联网 发布:iota 网络被攻击 编辑:程序博客网 时间:2024/06/05 19:28

题目地址:https://leetcode.com/problems/implement-strstr/

Implement strStr().

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

这个题目中的strStr(String haystack, String needle)类似于Java中String类的indexOf方法,如果needle是haystack的一个子字符串,则返回needle在haystack中第一次出现的位置,否则返回-1,表示不存在:

public class ImplementStrStr {    public static int strStr(String haystack, String needle) {        if (needle.length() > haystack.length())            return -1;        if (haystack.equals(needle))            return 0;        int haystackLen = haystack.length();        int needleLen = needle.length();        for (int i = 0; i <= haystackLen - needleLen; i++) {            if (haystack.substring(i, i + needleLen).equals(needle))                return i;        }        return -1;    }    public static void main(String[] args) {        System.out.println(strStr("This is the test case", "se"));    }}
0 0
原创粉丝点击