C++中二维字符数组中给定字符串的计数


以下问题是每日报纸填字游戏的示例,这里我们得到一个二维字符数组,问题陈述是从二维字符数组迷宫中找出给定的单词。搜索算法包括从上到下右到左以及反过来查找单个字符,但不包括对角线方向。

让我们通过例子来理解

输入- 字符串单词-LAYS

二维字符串[ ] - { "LOAPYS", "KAYSOT", "LAYSST", "MLVAYS", "LAYSAA", "LAOYLS" };

输出- 二维字符数组中给定字符串的计数:7

解释 - 给定一个字符串数组,我们必须从中找到单词“LAYS”,它可以在任何方向搜索,例如从上到下,从右到左,从下到上,以及从左到右。代码中的计数器标志在每次找到给定的搜索字符串时都会累加,最后返回计数作为结果。在这个例子中,我们可以看到LAYS出现了7次,即:

1->LOAPYS -LAYS-> 从左到右

2 ->SAYAOL-LAYS(从右到左)

3->LAYSST-LAYS(从左到右)

4->MLVAYS-LAYS(从左到右)

5->LAYSAA-LAYS(从左到右)

6->LAOYLS-LAYS(从左到右)

7->(从下到上) 红色LAYS

输入- 字符串单词- CAMP

二维字符串[ ] - { "BLOOKS", "BPOOLK", "KOHPKB", "BOLKOK", "LKIOOB", "LAHYBL" }

输出-二维字符数组中给定字符串的计数:0

解释 - 给定一个字符串数组,我们必须从中找到单词“LAYS”,它可以在任何方向搜索,例如从上到下,从右到左,从下到上,以及从左到右。代码中的计数器标志在每次找到给定的搜索字符串时都会累加,最后返回计数作为结果。在这个例子中,我们可以看到BOOK出现了0次。

下面程序中使用的方法如下

  • 我们得到一个字符串(单词)和一个字符串数组,以及一些实用程序变量,这些变量传递到findString()函数进行进一步处理。
  • 然后遍历矩阵中的字符,并选择一个字符来启动字符串。
  • 对于已选取的字符,我们根据算法在所有可能的方向上递归地查找给定字符串。
  • 如果找到匹配项,则递增计数器。
  • 完成第一个起始字符后,然后对下一个字符重复此过程。
  • 然后计算具有相应匹配项的计数总和。
  • 然后捕获最终答案,并打印结果。

示例

#include <bits/stdc++.h>
using namespace std;
int utilitySearch(string word, int r, int c, string arr[], int maxR, int maxC, int index) {
   int count = 0;
   if (r >= 0 && r <= maxR && c >= 0) {
      if (c <= maxC && word[index] == arr[r][c]) {
         char res = word[index];
         index = index + 1;
         arr[r][c] = 0;
         if (word[index] == 0) {
            count = 1;
         } else {
            count = count + utilitySearch(word, r, c + 1, arr, maxR, maxC, index);
            count = count + utilitySearch(word, r, c - 1, arr, maxR, maxC, index);
            count = count + utilitySearch(word, r + 1, c, arr, maxR, maxC, index);
            count = count + utilitySearch(word, r - 1, c, arr, maxR, maxC, index);
         }
         arr[r][c] = res;
      }
   }
   return count;
}

int findString(string word, int r, int c, string str[], int countR, int countC) {
   int count = 0;
   for (int i = 0; i < countR; ++i) {
      for (int j = 0; j < countC; ++j) {
         count = count + utilitySearch(word, i, j, str, countR - 1, countC - 1, 0);
      }
   }
   return count;
}

int main() {
      string word = "FLOOD";
      string inp[] = {"FPLIOKOD","FLOODYUT","YFLOODPU","FMLOSODT","FILPOYOD", FLOOOODE " };
         string str[(sizeof(inp) / sizeof( * inp))];
         for (int i = 0; i < (sizeof(inp) / sizeof( * inp)); ++i) {
            str[i] = inp[i];
         }
         cout << "Count of number of given string in 2D character array: " << findString(word, 0, 0, str, (sizeof(inp) / sizeof( * inp)), str[0].size());
         return 0;
}

如果我们运行上面的代码,它将生成以下输出:

输出

Count of number of given string in 2D character array: 6

更新于:2021年1月29日

522 次浏览

开启您的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.