字符串查找之暴力匹配法

问题描述:在长度为m的字符串source中,寻找长度为n的字符串target。如果source字符串中存在target字符串,则返回字符串target第一次在字符串source中出现的位置;如果不存在,则返回-1。

       一个最朴素的想法是使用暴力匹配法:将source中的字符与target中的字符逐一比较,如果source的当前字符与target的首字符相等,则继续比较它们的下一字符,直到出现了不等的字符或遍历了target所有字符。如果出现了不等的字符,则继续比较source的下一个和target的首字符,并重复上述过程。如果target的所有字符都被遍历了,则说明source字符串和target字符串相等。暴力匹配法的主要缺点是时间复杂度太高,需要O(n•m)时间。代码如下:

class Solution 
{
public:
    /*
     * @param source: source string to be scanned.
     * @param target: target string containing the sequence of characters to match
     * @return: a index to the first occurrence of target in source, or -1  if target is not part of source.
     */
    int strStr(const char *source, const char *target) 
    {
        if (source == nullptr || target == nullptr)
        {
            return -1;
        }
        
        if (strlen(source) < strlen(target))
        {
            return -1;
        }

        if (strlen(target) == 0)
        {
            return 0;
        }
        
        for (int i = 0; i < strlen(source) - strlen(target) + 1; i++)
        {
            int j = 0;
            for (j = 0; j < strlen(target); j++)
            {
                if (source[i+j] != target[j])
                {
                    break;
                }
            }
            
            if (j == strlen(target))
            {
                return i;
            }
        }
        
        return -1;
    }
};

猜你喜欢

转载自blog.csdn.net/yuanshine/article/details/81588136