檢查兩個單詞的和是否等於目標單詞


在這個問題中,我們將得到三個字串 str1、str2 和 str3,它們長度相同或不同,我們必須找到前兩個字串的和是否等於第三個字串。每個字串包含小於 'k' 的元素,這意味著 'a' 可以解碼為 '0','j' 可以解碼為 '9',我們可以將它們的和作為普通數字來計算。

示例

輸入1

字串 str1 = “abc”

字串 str2 = “bbe”

字串 str3 = “cdg”

輸出:

解釋 − 我們可以將 'a' 解碼為 '0','b' 解碼為 '1','c' 解碼為 '2','d' 解碼為 '3','e' 解碼為 '4','g' 解碼為 '6'。對映解碼後的值後,我們將得到最終字串“012”、“114”和“236”。我們可以將前兩個相加得到第三個值。

輸入2

字串 str1 = “abc”

字串 str2 = “abca”

字串 str3 = “aceb”

輸出: 否

解釋 − 我們可以將 'a' 解碼為 '0','b' 解碼為 '1','c' 解碼為 '2'。對映解碼後的值後,我們將得到最終字串“012”、“0120”和“0241”。我們不能將前兩個相加得到第三個值。

方法

我們已經看到了上面的例子,現在讓我們來看一下我們將要實現以獲得所需結果的主要方法步驟。

  • 首先,我們將建立一個函式,該函式將返回一個布林值以指示結果,並且它將採用所有三個給定字串作為引數。

  • 在函式中,我們首先將獲得所有三個字串的長度,這將有助於使用 while 或 for 迴圈遍歷它們。

  • 我們將反轉所有給定的字串,因為我們將要新增字串,並且我們從最後新增數字,所以為了從最後新增字串,我們將反轉它們以簡化過程。

  • 我們將使用 while 迴圈遍歷字串,並將建立一個名為 carry 的變數來儲存用於加法的數學進位。

  • 對於當前索引,我們將新增兩個字串當前索引的 ASCII 值,並將減去 'a' 的 ASCII 值以簡化求和,並將它們儲存在 carry 中。

  • 對於 carry 變數,我們將把模 10 值加上 'a' 新增到結果字串中,並將 carry 除以 10。

  • 遍歷字串後,我們將結果與給定的第三個字串進行比較,並且由於字串已經被反轉,因此我們可以直接進行比較。

  • 從主函式中,我們將呼叫該函式,並將根據返回值列印結果。

示例

#include <bits/stdc++.h>
using namespace std;
bool isEqual(string str1, string str2, string str3){
   // getting lengths of the string 
   int len1 = str1.size();
   int len2 = str2.size();
   int len3 = str3.size();   
   // reversing the strings 
   reverse(str1.begin(),str1.end());
   reverse(str2.begin(),str2.end());
   reverse(str3.begin(),str3.end());    
   // Getting the sum of the first two strings 
   string ans = "";
   int carry = 0; // variable to store the carry     
   int i=0, j=0;
   while(i < len1 || j < len2){
      if(i < len1 && j < len2){
         carry += str1[i]-'a'+str2[j]-'a';
         ans += 'a'+carry%10;
         carry /= 10;
         i++;
         j++;
      }
      else if(i == len1){
         carry += str2[j]-'a';
         ans += 'a'+carry%10;
         carry /= 10;
         j++;
      }
      else{
         carry += str1[i]-'a';
         ans += 'a'+carry%10;
         carry /= 10;
         i++;
      }
   }
   if(carry){
      ans += 'b';
   }
   return ans == str3; // returning the value on the basis of condition
}
int main(){
   // defining the given strings
   string str1 = "abc";
   string str2 = "bbe";
   string str3 = "bcg";    
   // calling the function to get if the given condition is true or not 
   if(isEqual(str1, str2, str3)){
      cout<<"Yes, the given strings have the sum equal to the given third string"<<endl;
   }
   else{
      cout<<"No, the given strings do not have the sum equal to the given third string"<<endl;
   }
   return 0;
}

輸出

Yes, the given strings have the sum equal to the given third string

時間和空間複雜度

上述程式碼的時間複雜度為 O(N),其中 N 是給定字串的長度。因為我們只對兩個字串各遍歷一次,並且我們反轉了所有字串。

上述程式碼的空間複雜度為 O(N),因為我們將結果儲存在額外的字串中。

結論

在上面的教程中,我們實現了一個程式來查詢給定的兩個字串的和是否等於給定的第三個字串。我們使用了 ASCII 值和基本數學的概念來新增字串。上述程式碼的時間複雜度為 O(N),空間複雜度相同。

更新於: 2023年5月17日

69 次瀏覽

開啟你的職業生涯

完成課程獲得認證

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