c# - 蛮力子串搜索算法
问题描述
我正在尝试使用蛮力技术进行简单的子字符串搜索,但出现错误。我对编程很陌生,所以请记住这一点。
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
}
推荐阅读
- html - 如何使表格元素水平溢出其父容器?
- floating-point - 可靠地确定浮点值向量是否(数字上)等距
- arrays - 从 Powershell 脚本导出多列 Excel 电子表格
- c++ - 如何正确设置 _MSVC_LANG 值?
- python - 到 Librosa 的 AudioSegment
- python - 'PySide2.QtWidgets.QApplication' 对象没有属性 'exec'
- php - Angular:如何使用 ng-repeat 中输入字段的更改来更新数据库
- java - Intellij Java Maven Gson 导入不起作用 - 包不存在
- python-3.x - Cythonizing python 3代码时未能实现有效的速度提升
- html - 为什么我的 html 使用 laravel 显示我的侧边栏和导航两次?