怎样建立网站挣钱拉新项目官方一手平台
笔试题:统计字符串中某一子串的字符个数:例如字符串aabbcd,有aabb:4,ab:2
哈哈,这道题是小编面试音视频龙头企业的笔试题,以下是我写的代码:如果有错误,希望可以指正!!!
解题思路:利用双指针i和j,在对比两个字符串出现不相等字符的字符时,需要对i和j进行回溯。举例如下:
(1)字符串aabbcd,有abb:3
(2)字符串aabbcd,有bcd:3
完整代码:
#include <iostream>
using namespace std;int mayBeSubStrCount(string str, string subStr) {int count = 0;int j = 0;for (int i = 0; i < str.length(); i++) {if (str[i] == subStr[j]) {j++;count++;}else {if (subStr[j] != '\0') {i = i - j;count = 0;j = 0;}}}return count;
}int main() {string str = "aabbcd";string subStr = "accd";cout << "Compare:" << endl;cout << "字符串1:"<<str << endl;cout << "字符串2:"<<subStr << endl;cout << "个数:"<<mayBeSubStrCount(str, subStr);return 0;
}
实验结果: