C++ 以“xAyB”的形式编码字符串,其中x和y基于数字的个数
在这个问题中,我们需要将字符串编码为xAyB格式,其中x是在相同索引处同时存在的字符串中数字的个数,而y是在不同索引处同时存在的字符串中数字的个数。
我们可以通过计算两个字符串中相同数字的个数来解决这个问题。此外,我们还可以计算两个字符串中同时在相同索引处存在的相同数字的总数来编码字符串。
问题说明 – 我们已经给出了长度相同的字符串str1和str2,其中只包含数字。我们需要以xAyB格式对给定的字符串进行编码。在这里,A和B是常量。
- X是str1和str2中相同索引出现的相同数字的总数。
-
Y是str1和str2中不同索引出现的相同数字的总数。
示例
输入
str1 = 4231, str2 = 4623
输出
1A2B
解释 - 在输入字符串中,’2′ 是一个共同的数字,并且在两个字符串的相同索引中存在。
在两个字符串中,’4′ 和 ‘3’ 也是共同存在的,但它们的索引不同。
输入
str1 = 1234, str2 = 1234
输出结果
4A0B
解释 - 在给定的字符串中,所有字符都相同且存在于相同的索引位置。所以,x 是 4,y 是 0。
输入
str1 = 6543, str2 = 3456;
输出
0A4B
说明 – 给定的字符串包含所有相同的字符,但位于不同的索引位置。所以,x是0,y是4。
方法
在这个方法中,我们将找到两个字符串中相同数字的数量。然后,我们将找到在相同索引位置上相同数字的数量,并利用这个数量来计算位于不同索引位置上相同数字的总数量。
算法
步骤1 - 使用toString()方法将整数转换为字符串。
步骤2 - 初始化freq1和freq2两个大小为10的列表,用于存储str1和str2中数字的频率。
步骤3 - 依次遍历str1和str2,计算数字的频率。
步骤4 - 将sameDigits变量初始化为0,用于存储两个字符串中相同数字的数量,将sameIndex初始化为0,用于存储相同索引位置上相同数字的数量。
步骤5 - 进行0到9的迭代,将freq1[p]和freq2[p]中的较小值加到sameDigits变量的值上。
步骤6 - 现在,遍历两个字符串,如果任意字符在两个字符串中的第p个索引位置上相同,则将sameIndex的值增加1。
步骤7 - 将sameIndex从sameDigits中减去。
步骤8 - 编码字符串。这里,sameIndex是x的值,sameDigits是y的值。
步骤9 - 返回编码后的字符串。
示例
#include <bits/stdc++.h>
using namespace std;
string getEncodedStr(int str1, int str2) {
// Conver numeric strings to strings
string temp1 = to_string(str1), temp2 = to_string(str2);
// Calculate sameDigits of digits in str1
vector<int> freq1(10, 0);
for (char ch : temp1)
freq1[ch - '0']++;
// Calculate sameDigits of digits in str2
vector<int> freq2(10, 0);
for (char ch : temp2)
freq2[ch - '0']++;
int sameDigits = 0, sameIndex = 0;
// Find the total number of counts of the same digits
for (int p = 0; p < 10; p++)
sameDigits += min(freq1[p], freq2[p]);
// Find the total number of counts of the same digits on the same indices
for (int p = 0; p < temp1.length() && temp2.length(); p++) {
if (temp1[p] == temp2[p]) {
sameIndex++;
}
}
// Get the total number of the same digits on different indices
sameDigits -= sameIndex;
// Encode the string
string ans = "" + to_string(sameIndex) + "A" + to_string(sameDigits) + "B";
return ans;
}
int main() {
int str1 = 4231, str2 = 4623;
cout << "The encoded string is - " << getEncodedStr(str1, str2) << endl;
return 0;
}
输出
The encoded string is - 1A2B
时间复杂度 - O(N)用于遍历字符串并计算数字出现的频率。
空间复杂度 - O(1),因为我们使用常数空间来计算10个数字的频率。
我们学会了通过计算相同数字在同一或不同索引处出现的次数来对字符串进行编码。程序员可能会尝试使用相同或不同索引处出现的数字的总和来对字符串进行编码。