C++算法:判断字符串子序列
C++算法:判断字符串子序列
以下是使用C++编写的程序,用于判断字符串B是否为字符串A的子序列:
#include <iostream>
#include <string>
using namespace std;
boolean isSubsequence(string A, string B) {
int ptrA = 0;
int ptrB = 0;
while (ptrA < A.length() && ptrB < B.length()) {
if (A[ptrA] == B[ptrB]) {
ptrB++;
}
ptrA++;
}
return ptrB == B.length();
}
int main() {
string A = 'BROWAHTRUDOING';
string B = 'TRU';
if (isSubsequence(A, B)) {
cout << 'B是A的子序列' << endl;
} else {
cout << 'B不是A的子序列' << endl;
}
return 0;
}
在这个例子中,A的值为'BROWAHTRUDOING',B的值为'TRU'。通过运行上述程序,可以得到输出结果为'B是A的子序列'。
代码解释:
- 该程序使用双指针方法,
ptrA指向字符串A,ptrB指向字符串B。 - 遍历字符串
A,如果A[ptrA]等于B[ptrB],则ptrB向后移动一位。 - 如果
ptrB最终移动到B的末尾,则说明B中所有字符都在A中出现过,且顺序一致,因此B是A的子序列。
该算法的时间复杂度为O(n),其中n为字符串A的长度。
原文地址: https://www.cveoy.top/t/topic/KwZ 著作权归作者所有。请勿转载和采集!