微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

蛮力子串搜索算法

如何解决蛮力子串搜索算法

我正在尝试使用蛮力技术进行简单的子字符串搜索,但出现错误。我对编程很陌生,所以请记住这一点。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;

namespace Csharp_Training
{
    
    class Program
    {
        public static int Search(string Text,string Pattern,int N,int M)
        {
            for (int i = 0; i < N - M; i++)
            {
                int j;
                for (j = 0; j < M; j++)
                {
                    if (Text[i + j] != Pattern[i])
                    {
                        break;
                    }
                    if (j == M) return i;
                }
            }
            return N;
        }
        static void Main(string[] args)
        {
            string Txt = "this is a test";
            string Pttrn = "test";
            int LN = Txt.Length;
            int LM = Pttrn.Length;
            int result = Search(Txt,Pttrn,LN,LM);
            Console.Write(result);
        }
    }          
}

解决方法

要使其正常运行,有几个问题需要解决。

public static int Search(string Text,string Pattern,int N,int M)
{
    for (int i = 0; i <= N - M; i++) // Not i < N - M
    {
        int j;
        for (j = 0; j < M; j++)
        {
            if (Text[i + j] != Pattern[j]) // Not Pattern[i]
            {
                break;
            }
            //if (j == M) return i;
        }
        if (j == M) return i; // Moved outside the inner loop
    }
    return -1; // Not return N
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。