实现strStr
阅读原文时间:2023年07月11日阅读:2

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

Constraints:

haystack and needle consist only of lowercase English characters.

实现的关键就是使用substring()方法,将整个字符串分成与目标字符串的长度相同的小段,然后使用equals方法比较,如果有相同的,则返回开始的角标

1 package easy;
2
3 class SolutionStr{
4 public int strStr(String hystack,String needle){
5 int len1 = hystack.length();
6 int len2 = needle.length();
7 if(len2 > len1){
8 return -1;
9 }
10 if(len2 == 0){
11 return 0;
12 }
13 for(int i = 0;i < len1 - len2 + 1; ++i){
14 if(hystack.substring(i,i+len2).equals(needle)){
15 return i;
16 }
17 }
18 return -1;
19 }
20 }
21 public class ImplstrStr {
22 public static void main(String[] args) {
23 SolutionStr solution = new SolutionStr();
24 System.out.println(solution.strStr("leetcode","ee"));
25 }
26 }