在字符串网格中计算字符串短语

Counting the string phrase in String Grid

本文关键字:字符串 短语 计算 网格      更新时间:2023-10-16

您获得了一个n*m网格,其中包含较低的案例英语字母。" saba"一词在网格中水平,垂直和对角线出现多少次?

水平,垂直和对角线计数。

#include<iostream> 
#include <vector>
#include <string>
using namespace std;
int TotalCount(vector<string> Str, int ItemCount)
{
string Text = "saba";
string VerticalString = "";
string DiagonalOneString = "";
string DiagonalTwoString = "";
int count = 0;
for (int i = 0; i < ItemCount; ++i)
{
    string& currentRow = Str[i];
    VerticalString = VerticalString.append(&currentRow.at(0));
    DiagonalOneString = DiagonalOneString.append(&currentRow.at(i));
    DiagonalTwoString = 
    DiagonalTwoString.append(&currentRow.at(currentRow.length() - 1 - i));
    if ((currentRow.find(Text) != string::npos) || (VerticalString.find(Text) != string::npos) || (DiagonalOneString.find(Text) != string::npos) || (DiagonalTwoString.find(Text) != string::npos))
    {
        count++;
    }
}
return count;
}
int main()
{
int total = 0;
int row;
cin >> row;
vector<string> rows;
// read each row and append to the "rows" vector
for (int r = 0; r < row; r++)
{
    string line;
    cin >> line;
    rows.push_back(line);
}
cout << TotalCount(rows, row);
return 0;
}

输入格式

第一行:两个整数n和m,其中n表示(1&lt; = n,m&lt; = 100(行的数量和m表示网格中的列数下一个n行:每行必须包含一个长度为m的字符串,该长度仅包含低点英文字母

Sample Input
5 5
safer
amjad
babol
aaron
songs
Expected Output
2

似乎垂直弦复制了整个字符串,而不是在指定位置复制字符。我没有得到预期的计数。可以请有人让我知道为什么计数出错了吗?

当垂直字符串为 saba时, count将增加。但是当您的垂直字符串为sabas时,count将再次增加。

另外,您可能打算搜索对角线,除了两个角落之间的两个。仅查看2个对角线可以忽略有效的命中。

可能需要阅读两个方向。

我的建议是将问题分解为从每个水平行计算命中,计算每个垂直行的命中(可以转移矩阵并重新使用第一个功能(,计数对角线(向西到西南到西南(,最后计数对角线(西北到东南(。即,为每个函数献给每个功能,并总结结果。

您正在测试的打印字符串也将极大地帮助您进行调试。