[LeetCode 28]Implement strStr()

来源:互联网 发布:sql多个统计结果 编辑:程序博客网 时间:2024/05/19 11:50

题目链接:implement-strstr


/** * Implement strStr().Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. * */public class ImplementStrStr {//72 / 72 test cases passed.//Status: Accepted//Runtime: 270 ms//Submitted: 0 minutes ago//暴力法 时间复杂度 O(mn) 空间复杂度o(1)    static int strStr(String haystack, String needle) {    for (int i = 0; i <= haystack.length() - needle.length(); i++) {int j = 0;    for (; j < needle.length(); j++) {if(needle.charAt(j) != haystack.charAt(i + j)) break;}if(j == needle.length()) return i;}    return -1;    }public static void main(String[] args) {System.out.println(strStr("", ""));System.out.println(strStr("a", "a"));}}


0 0
原创粉丝点击