通过将每个数字替换为 X 的乘积,检查是否可以在 M 步中将 S 转换为 Target
给定两个数字字符串S和Target,以及整数X, M 。任务是检查是否可以使用以下操作将字符串S转换为字符串Target :
- 在一个操作中,需要将S中的每个数字替换为其与X 的乘积,即S[i] = (S[I]*X)。
- 上述操作必须准确地进行M次。
例子:
Input: S = “1234”, Target = “2550525100”, X = 5, M = 2
Output: YES
Explanation:
Initially S=1234
After the 1st, level S becomes =5101520
After the 2nd level, S=2550525100
Thus, we are able to make Target string So print YES
Input: S = “53783”, Target = “2893653”, X = 2, M = 3
Output: NO
方法:这是一个基于实现的问题,简单地从左到右遍历并在原始字符串中存在的每个数字中乘以X。使用给定的字符串S 执行此 M 次,并检查是否可以将原始字符串S转换为 Target 字符串。
下面是上述方法的实现:
C++
// C++ program to check
// If strings are Equal or not
#include
using namespace std;
void makestring(string S, string Target, int X, int M)
{
// Out of X and M if any one
// having value zero then just compare
// original string To Target string
if (X == 0 || M == 0) {
if (S == Target) {
cout << "YES" << endl;
}
}
else {
vector v1;
for (int i = 0; i < S.length(); i++) {
// character to integer
int val = S[i] - '0';
// convert into string
string a = to_string(val);
v1.push_back(a);
}
while (M--) {
vector v;
for (int i = 0; i < v1.size(); i++) {
for (int j = 0; j < v1[i].size(); j++) {
int temp = v1[i][j] - '0';
// multiply X into given integer
temp = temp * X;
v.push_back(to_string(temp));
}
}
v1 = v;
}
// Store all character from vector
// of string into temp string
string temp = "";
for (int i = 0; i < v1.size(); i++) {
for (int j = 0; j < v1[i].size(); j++) {
temp.push_back(v1[i][j]);
}
}
// Compare both Target and temp
if (temp == Target) {
cout << "YES" << endl;
}
else {
cout << "NO" << endl;
}
}
}
// Driver Code
int main()
{
string S = "1234";
string Target = "2550525100";
int X = 5;
int M = 2;
makestring(S, Target, X, M);
return 0;
}
Javascript
输出
YES
时间复杂度: O(N* N* M)
辅助空间: O(N)