【LeetCode】 Implement strStr()

序号:28

难度:easy

题目简述:

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

字符串匹配问题,目前使用Brute-Force的方法解决,听说KMP是解决这类问题的主要方法,之后再学  。

 1 class Solution {
 2     public int strStr(String haystack, String needle) {
 3         String h = haystack;
 4         String n = needle;
 5         if("".equals(n)) return 0;
 6        for(int i = 0;i <= h.length() - n.length();i++){
 7            for(int j = 0; h.charAt(i+j) == n.charAt(j) && j < n.length();j++)
 8                if(j == n.length() - 1) return i;
 9        }
10         return -1;
11     }
12 }

 

posted @ 2019-11-06 17:37  LinM狂想曲  阅读(107)  评论(0)    收藏  举报