检查两个单词的和是否等于目标单词
在这个问题中,我们将得到三个字符串 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),空间复杂度相同。
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP