LeetCode OJ:Implement strStr()

Implement strStr()

 

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.


算法思想:

循环扫描,比较直白

class Solution {
public:
    char *strStr(char *haystack, char *needle) {
        
        int size = strlen(haystack) - strlen(needle);
        for (int i = 0; i <= size; i++) {  
            bool flag = true;  
            for (int j = 0; j < strlen(needle); j++) {  
                if (haystack[i + j] != needle[j]) {  
                    flag = false;  
                    break;  
                }  
            }  
            if (flag == true) {  
                return &haystack[i];  
            }  
        }  
        return NULL;  
    }
};

2、简单匹配算法BF算法

class Solution {
public:
    char *strStr(char *haystack, char *needle) {
        
        int slen = strlen(haystack);
        int tlen = strlen(needle);
        int i = 0 ,j = 0;
        
        while ( i+j < slen && j < tlen){
            if ( haystack[i+j] == needle[j] ){
                j ++;
            }
            else
            {
                i ++;
                j = 0;
            }
        }
        if ( j >= tlen)
            return &haystack[i];
        else
            return NULL;
    }
};



3、KMP算法

KMP算法

class Solution {
public:
    //代码4-1    
    //修正后的求next数组各值的函数代码    
    void get_nextval(char const* ptrn, int plen, int* nextval)    
    {    
        int i = 0;     
        nextval[i] = -1;    
        int j = -1;    
        while( i < plen-1 )    
        {    
            if( j == -1 || ptrn[i] == ptrn[j] )   //循环的if部分    
            {    
                ++i;    
                ++j;    
                   
                if( ptrn[i] != ptrn[j] )     
                    nextval[i] = j;          
                else    
                    nextval[i] = nextval[j];    
            }    
            else                                     
                j = nextval[j];    
        }    
    }
    char *strStr(char *haystack, char *needle) {
        
        int slen = strlen(haystack);
        int tlen = strlen(needle);
        int i = 0 ,j = 0;
        
        int *nextval=new int[tlen];
        get_nextval(needle,tlen,nextval);
        
        while ( i+j < slen && j < tlen){
            if ( j == -1 || haystack[i+j] == needle[j] ){
                j ++;
            }
            else
            {
                i ++;
                j = nextval[j];
            }
        }
        if ( j >= tlen)
            return &haystack[i];
        else
            return NULL;
    }
};




你可能感兴趣的:(LeetCode)