码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode------Implement strStr()

时间:2015-01-23 13:10:56      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:

标题: Implement strStr()
通过率: 21.8%
难度: 简单

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button  to reset your code definition.

本题意思就是字符串匹配,返回匹配到的开头位置,那么我首先想到了KMP算法,但是KMP算法我已经完全忘记了,于是我想先写个暴力解法就是从头开始匹配,不相同的话到下个位置开始匹配。

惊人的是我写完代码并且通过以后我去看那个solution,上面竟然说暴力解法是最优的解法,面试的时候直接用暴力解法就行了,并且字符串越长暴力解法的优势越明显,那么具体代码如下:

 1 public class Solution {
 2     public int strStr(String haystack, String needle) {
 3         int stacklen=haystack.length();
 4         int needlelen=needle.length();
 5         int j=0;
 6         if(needlelen==0&&stacklen==0)return 0;
 7         if(needlelen==0&&stacklen!=0) return 0;
 8         if(needlelen>stacklen) return -1;
 9         for(int i=0;i<=stacklen-needlelen;i++){
10             int tmp=i;
11             for(j=0;j<needlelen;j++){
12                 if(needle.charAt(j)!=haystack.charAt(tmp)) break;
13                 tmp++;
14             }
15             if(j==needlelen) return i;
16         }
17         return -1;
18     }
19 }

 下面我把solution的贴出来:

O(nm) runtime, O(1) space – Brute force:

You could demonstrate to your interviewer that this problem can be solved using known efficient algorithms such as Rabin-Karp algorithm, KMP algorithm, and the Boyer- Moore algorithm. Since these algorithms are usually studied in an advanced algorithms class, it is sufficient to solve it using the most direct method in an interview – The brute force method.

The brute force method is straightforward to implement. We scan the needle with the haystack from its first position and start matching all subsequent letters one by one. If one of the letters does not match, we start over again with the next position in the haystack.

The key is to implement the solution cleanly without dealing with each edge case separately.

 

leetcode------Implement strStr()

标签:

原文地址:http://www.cnblogs.com/pkuYang/p/4243642.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!