You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

暴力字符串匹配(bfSM)算法无输出问题求助

Fixing Your Brute-Force String Matching Code

Hey there! I see two key issues that are causing your code to either show no output or miss potential matches. Let's break them down and fix things up:

1. You're not printing the result

Your main function calls bruteForceSM(pattern, text) correctly, but it doesn't do anything with the returned integer. That's why your console only shows the process exit code and no actual match index. You need to add a cout statement to output the result.

2. The loop condition in bruteForceSM is incorrect

The line for (int i = 0; i < (t.size() - p.size()); i++) will skip the last possible starting position for the pattern. For example, if your text is length 20 and pattern is length 5, the last valid starting index is 15 (20-5). But your loop stops at i=14 because of the < operator. You should change it to <= to include that final position.

Corrected Code

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iomanip>
#include<stdio.h>
#include<string.h>
using namespace std;

int bruteForceSM(string p, string t) {
    // Fixed loop condition to include the last possible starting index
    for (int i = 0; i <= (t.size() - p.size()); i++) {
        int j = 0;
        while(j < p.size() && p[j] == t[i + j]) {
            j++;
        }
        if (j == p.size()) {
            return i;
        }
    }
    return -1;
}

int main(){
    string text = "sally sells seashells by the seashore";
    string pattern = "shell";
    // Store the result and print it
    int result = bruteForceSM(pattern, text);
    cout << "Match found at index: " << result << endl;
    return 0;
}

What This Fixes

  • Now the code will print either the starting index of the first match (which should be 17 for your sample text and pattern) or -1 if no match exists.
  • The loop condition ensures we check every possible starting position where the pattern could fit in the text.

内容的提问来源于stack exchange,提问作者Ilona Matta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 14:07:35