#include<iostream> #include<algorithm> #include<vector> #include<string> using namespace std; int judge(string s, int m, string t, int n) { int i = 0, j = 0; while (i < n) { if (s[j] == t[i]) { i++; j++; if (i != n && j == m) //特殊情况:adh不是ahd的子序列 return 0; } else { j++; if (j == m) return 0; } } return 1; } int main() { int ans = 0; string s,t; cin >> s; cin >>t; int len = s.size(); for (int i = 0,right=len-1; i < s.size() - 1; ++i) { for (int j = s.size() - 1; j >= 0&&i!=j; --j) { string tmp_s=s.substr(i,j); int m = tmp_s.size(); int n = t.size() ; if (judge(tmp_s, m, t, n)) { ans++; } } } cout << ans; return 0; }
时间: 2023-12-03 08:05:10 浏览: 61
下面是对代码的一些优化建议:
1. 减少头文件的数量:只需要包含 `<iostream>` 就可以使用 `std::string`,不需要包含 `<algorithm>` 和 `<vector>`。
2. 减少重复计算:在 `for` 循环中,可以将 `s.size() - 1` 保存为变量 `len`,这样就可以避免在每个循环中重复计算。
3. 减少变量的使用:在 `judge` 函数中,可以将 `i` 和 `j` 参数合并为一个参数,从而避免使用变量 `i` 和 `j`。
4. 避免不必要的字符串拷贝:在 `for` 循环中,可以使用 `s.substr(i, j - i)` 来获取子串,避免创建不必要的临时字符串对象。
5. 减少函数调用次数:可以将 `t.size()` 提前保存到变量 `n` 中,避免在 `judge` 函数中多次计算。
6. 使用前缀和优化判断子串是否为前缀的操作:可以先将 `t` 的前缀和保存到数组 `prefix` 中,然后在 `judge` 函数中使用二分查找快速判断子串是否为前缀。
下面是优化后的代码:
相关问题
#include <iostream> #include <vector> #include <algorithm> #include <queue> using namespace std; s
这段代码是C++语言中的头文件引入部分,用于在程序中引入iostream、vector、algorithm和queue等库,以便使用这些库中的函数和类。其中,iostream库提供了C++输入输出流的功能,vector库提供了可变大小的数组容器,algorithm库提供了常用的算法函数,queue库提供了队列容器的支持。通过这些库,可以方便地进行程序开发和数据处理。
#include <iostream> #include <fstream> #include <vector> #include <string> using namespace std; //
这是一段C++程序的头文件部分,包含了一些标准库的头文件,具体介绍如下:
1. iostream:提供了输入输出流的基本功能,如cin、cout等。
2. fstream:提供了文件操作相关的功能,如读写文件等。
3. vector:提供了可变大小数组的功能,可以方便地进行动态管理。
4. string:提供了字符串相关的功能,如字符串的拼接、截取等。
其中,using namespace std; 表示使用标准命名空间,可以简化程序中的代码。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![text/plain](https://img-home.csdnimg.cn/images/20250102104920.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![text/plain](https://img-home.csdnimg.cn/images/20250102104920.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)