28. Implement strStr()

题目链接:https://leetcode.com/problems/implement-strstr/

解题思路:

这其实是字符串匹配的问题,找到子串在字符串中出现的第一个位置,如果不存在返回-1。

两层循环,第一层i循环是大的字符串,第二层j循环是小的字符串,如果两个匹配出现了不等的情况,那么这个i就要+1,跳出第二层循环。

如果一直出现到j=n,说明小的字符串每一个位置都能在i中找到,那就返回当前指针i。

 1 class Solution {
 2     public int strStr(String haystack, String needle) {
 3         
 4         
 5         
 6         int m = haystack.length();
 7         int n = needle.length();
 8         
 9         if(n==0)
10             return 0;
11         if(n>m)
12             return -1;
13         
14         for(int i=0;i<=m-n;i++)
15         {
16             int j=0;
17             
18             while(j<n)
19             {
20                 if(haystack.charAt(i+j)!=needle.charAt(j))
21                     break;
22                 j++;
23             }
24             if(j==n)
25                 return i;
26         }
27         return -1;
28     }
29 }
原文地址:https://www.cnblogs.com/wangyufeiaichiyu/p/10833627.html