首页 > 解决方案 > 蛮力子串搜索算法

问题描述

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

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);
        }
    }          
}

标签: c#algorithmsearchsubstringbrute-force

解决方案


有几个问题需要解决才能使其正常工作。

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
}

推荐阅读