首页 > 其他 > 详细

28. Implement strStr()

时间:2019-05-08 19:42:39      阅读:131      评论:0      收藏:0      [点我收藏+]

题目链接: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 }

 

28. Implement strStr()

原文:https://www.cnblogs.com/wangyufeiaichiyu/p/10833627.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!