[Simple algorithm] 18. Implement strStr()

topic:

Implement the strStr() function.

Given a haystack string and a needle string, find the first position (0-based) in the haystack string where the needle string occurs. Returns -1 if not   present .

Example 1 :

Input: haystack = " hello " , needle = " ll " 
Output: 2 
Example 2 :

Input: haystack = " aaaaa " , needle = " bba " 
Output: - 1
illustrate:

What value should we return when needle is the empty string? This is a good question to ask in an interview.
For this problem, we should return 0 
when needle is the empty string . This matches the definition of strstr() in C and indexOf() in Java.

1. Problem solving ideas:

This question is relatively simple, you can directly find and compare. There is no need to consider more complex algorithms such as KMP algorithm.

code show as below:

class Solution {
public:
    int strStr(string haystack, string needle) {
     int n;
     bool flag = false;
    
     if(needle.size() < 0 || needle.size() > haystack.size()){
         return -1;
     }
        
        
     for(int i = 0;i <= haystack.size() - needle.size();++i){
         flag = true;
         for(int j = 0;j < needle.size();++j){
             if(haystack[i+j]!=needle[j]){
                 flag = false;
                 break;
             }
         }
         if(flag){
             return i;
         }
     }
     
      return -1;
    }
};

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325252273&siteId=291194637