问题:
如果X中的数字序列形成Y中数字序列的子字符串,则输出" X是Y"的子字符串;否则,如果X中的数字序列形成Y中数字序列的子序列,则它输出" X是Y"的子序列;否则,它输出" X既不是Y"的子串也不是子序列。
不要在此程序中使用数组或字符串
输出应如下
输入Y:239847239
输入X:847
X是Y的子串
输入Y:239847239
输入X:3923
X是Y
的后续序列输入Y:239847239
输入X:489
X既不是Y的子串也不是Y
的子序列以下是我到目前为止所得到的...(由于我无能为力,所以没有为后续编码做任何事情)
我知道我的编码非常低效,仅适用于上述模型输出。任何改进或评论如何解决这个问题将不胜感激。
#include <cmath>
#include <iostream>
using namespace std;
int main() {
cout << "Enter Y: " ;
int Y;
cin >> Y;
cout << "Enter X: ";
int X;
cin >> X;
if (Y >= X){ // Below are all the possibilities of substrings up to 9 decimal places.
if( X == (Y % 10)) cout << "X is substring of Y";
else if (X == (Y % 100)) cout << "X is substring of Y";
else if (X == (Y % 1000)) cout << "X is substring of Y";
else if (X == (Y % 10000)) cout << "X is substring of Y";
else if (X == (Y % 100000)) cout << "X is substring of Y";
else if (X == (Y % 1000000)) cout << "X is substring of Y";
else if (X == (Y % 10000000)) cout << "X is substring of Y";
else if (X == (Y % 100000000)) cout << "X is substring of Y";
else if (X == (Y % 1000000000)) cout << "X is substring of Y";
else cout << "X is neither substring nor subsequence of Y";
}
else cout << "neither subsequence nor subset"; // prints out when Y is less than X.
return 0;
}
答案 0 :(得分:0)
这是我到目前为止所得到的:
<强>子串强>
bool substring(long x, long y){
double auxX = x;
int power = 0;
while (auxX >= 1){
auxX /= 10;
++power;
}
int mask = pow(10, power);
int reminder;
while (y > 0){
reminder = y % mask;
if (reminder == x){
return true;
}
y /= 10;
}
return false;
}
<强>子序列强>
bool subsequence(long x, long y){
int lastX;
int lastY;
while (y > 0){
lastX = x % 10;
lastY = y % 10;
if (lastX == lastY){
x /= 10;
if (x <= 0){
return true;
}
}
y /= 10;
}
return false;
}
主要强>
int main()
{
long x = 21;
long y = 469721481;
if (substring(x, y)){
cout << x << " is substring of " << y << std::endl;
}
else if (subsequence(x, y)){
cout << x << " is subsequence of " << y << std::endl;
}
else{
cout << x << " is neither substring nor subsquence of " << y << std::endl;
}
return 0;
}
我已经测试了一些情况并且似乎工作正常,但你应测试边缘情况(多次重复相同模式,一位数字,零等)并修饰这个片段
答案 1 :(得分:0)
也许尝试以下代码:
class Solution {
public:
bool isSubsequence(string s, string t) {
auto i = s.begin();
for(char c : t) i += (*i == c);
return i == s.end();
}
};
或此 Python 版本:
def isSubsequence(s: str, t: str) -> bool:
it = iter(t)
return all(ch in it for ch in s)