Thursday, January 8, 2015

Implement strStr() (LeetCode Two Pointers)

Question: Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Idea: I used the brute force method by comparing the substrings one by one. There are other algorithms, e.g. KMP which can achieve better performance.

Time: O(n^2) Space: O(1)

Code:
 public class Solution {  
   public int strStr(String haystack, String needle) {  
     for(int i=0;i<haystack.length()-needle.length()+1;i++)  
     {  
       int j=0;  
       for(j=0;j<needle.length();j++)  
       {  
         if(haystack.charAt(i+j)!=needle.charAt(j))  
           break;  
       }  
       if(j==needle.length())  
         return i;  
     }  
     return -1;  
   }  
 }  

No comments:

Post a Comment