【发布时间】:2021-09-21 10:06:12
【问题描述】:
给定和字符串,我们需要找出 1 大于 0 的子字符串的总数。
我使用动态编程解决了这个问题,但我无法提出解决方案,我成功编写了一个简单的逻辑,但我无法优化代码(即超过时间限制)
任何关于优化的帮助或对新方法的建议都将得到充分的帮助。 以下代码的时间复杂度为 O(n^3) 任何降低时间复杂度的解决方案都会有所帮助。
提前致谢。
我使用的代码:
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main(){
int tc =0; //total count
string st; //original string
getline(cin,st);
int lent = st.size(); //size of string
for(int i =0;i<lent;i++){ //loop to generate all possible substrings
int j = lent-1;
while(j>=i){
string st1(st.begin()+i,st.end()-j+i); // A substring
int c1 = count(st1.begin(),st1.end(),'1'); // count of 1's in substring
if(c1 > st1.size()-c1) tc++; // Condition to check if 1's are more
j--;
}
}
cout << tc; // Print total substrings
}
注意:子字符串是字符串中连续的字符序列。 有关子字符串的更多信息,请访问Wikipedia
【问题讨论】:
-
1 总是大于 0。你的意思是 1 的数量大于 0 的数量吗?
-
这是 O(n^3),计数也是 O(n)。获得 O(n^2) 不应该那么难。
-
@463035818_is_not_a_number 是的,该子字符串中 1 的总数应大于其中 0 的总数。
-
@maraca 感谢编辑。
-
检查我的答案,你可以在
O(log n)计算它
标签: c++ algorithm optimization time-complexity substring