C++中計算刪除一個字元後等於兩個字串之一的字串數量


給定兩個不同的字串,例如s1和s2,任務是組合s1和s2的唯一字母形成字串S,然後檢查從字串S中刪除一個字元後是否形成等於字串s1或s2的字串。

例如

輸入 - 字串S1 = "utter",字串S2 = "butter";

輸出 - 刪除一個字元後等於兩個字串之一的字串數量為:1

解釋 - 給定字串s1和s2,我們將形成字串S,即'butter',如果我們從字串S中刪除字母'b',它將變成'utter',這等於字串s1,因此計數為1。

輸入 - 字串S1 = "fat",字串S2 = "rat";

輸出 - 刪除一個字元後等於兩個字串之一的字串數量為:2

解釋 - 給定字串s1和s2,我們將形成字串S,即'frat',如果我們從字串S中刪除字母'r',它將變成'fat',這等於字串s1;如果我們刪除字母'f',它將變成'rat',這等於字串s2,因此計數為2。

下面程式中使用的演算法如下:

  • 宣告兩個字串s1和s2,計算字串s1的大小,並將資料傳遞給函式進行進一步處理。
  • 宣告一個變數count並將其設定為2,因為最大可能的輸出是2。
  • 宣告兩個臨時變數start和end用於迴圈遍歷。
  • 從0到字串s1的大小開始FOR迴圈,在迴圈內檢查IF s1[i]不等於s2,則將start設定為i並中斷。
  • 從i到字串s1大小減1開始另一個FOR迴圈,在迴圈內檢查IF s1不等於s2,則將end設定為i並中斷。
  • 檢查IF end的值小於start,則將count設定為26 * (字串s1的大小 + 1)並返回count。
  • ELSE IF 檢查start等於end,則返回count。
  • ELSE,從i到start + 1到end開始FOR迴圈,在迴圈內檢查IF s1[i]不等於s2[i-1],則將count減1並中斷。
  • 從i到start + 1到end開始FOR迴圈,檢查IF s1[i-1]不等於s2[i],則將count減1並中斷。
  • 返回count。
  • 列印結果。

示例

線上演示

#include <bits/stdc++.h>
using namespace std;

int equal_removal(string S1, string S2, int size_S1) {
   int count = 2;
   int start;
   int end;

   for (int i = 0; i < size_S1; ++i) {
      if (S1[i] != S2[i]) {
         start = i;
         break;
      }
   }
   for (int i = size_S1 - 1; i >= 0; i--) {
      if (S1[i] != S2[i]) {
         end = i;
         break;
      }
   }
   if (end < start) {
      count = 26 * (size_S1 + 1);
      return count;
   } else if (start == end) {
      return count;
   } else {
      for (int i = start + 1; i <= end; i++) {
         if (S1[i] != S2[i - 1]) {
            count--;
            break;
         }
      }
      for (int i = start + 1; i <= end; i++) {
         if (S1[i - 1] != S2[i]) {
            count--;
            break;
         }
      }
      return count;
   }
}
int main() {
   string S1 = "utter";
   string S2 = "butter";
   int size_S1 = S1.length();
   cout << "Count of strings that become equal to one of the two strings after one removal are: " << equal_removal(S1, S2, size_S1);
   return 0;
}

如果我們執行上面的程式碼,它將生成以下輸出:

輸出

Count of strings that become equal to one of the two strings after one removal are: 1

更新於: 2021年1月29日

443 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.