C++ 无重复字符的子字符串计数(具有唯一字符的子字符串总数)
我在这段代码中使用了获取和发布策略,但没有给出结果。正如我所检查的,我认为它没有进入内部循环C++ 无重复字符的子字符串计数(具有唯一字符的子字符串总数),c++,C++,我在这段代码中使用了获取和发布策略,但没有给出结果。正如我所检查的,我认为它没有进入内部循环 #include <bits/stdc++.h> using namespace std; int main() { // Write C++ code here string s = "abc"; int ans =0; int i= -1,j=-1; unordered_map<char,int> m; wh
#include <bits/stdc++.h>
using namespace std;
int main() {
// Write C++ code here
string s = "abc";
int ans =0;
int i= -1,j=-1;
unordered_map<char,int> m;
while(true){
bool f1 = false;
bool f2 = false;
while(i< s.length()-1){
//aquire
f1 = true;
i++;
char ch = s[i];
m[ch]++;
if(m[ch]==2){
break;
}else{
ans += i-j;
}
}
while(j<i){
//release
f2 = true;
j++;
char ch = s[j];
m[ch]--;
if(m[ch]==1){
ans+= i-j;
break;
}
}
if(f1 == false && f2 == false){
break;
}
}
cout<<ans;
return 0;
}`
根据这段代码,答案应该是6=a,b,c,ab,bc,abc。我会稍微重写一下循环
#include <iostream>
#include <iterator>
#include <string>
#include <unordered_set>
unsigned count_substr_without_repeating_chars(const std::string& s) {
unsigned r = 0;
for(unsigned f = 0; f < s.size(); ++f) { // first char
std::unordered_set<char> seen;
for(unsigned l = f; l < s.size(); ++l) { // last char
auto[it, inserted] = seen.emplace(s[l]); // try inserting
if(not inserted) break; // no need to investigate this further
++r;
//std::cout << std::string(&s[f], std::next(&s[l])) << '\n';
}
}
return r;
}
int main() {
std::string s = "abca";
std::cout << count_substr_without_repeating_chars(s) << '\n'; // prints 9
}
为什么这个算法如此复杂?子字符串的数量不是等于分隔符的数量+1吗?我还说过,如果字符串是abca,则不重复字符。答案是a、a、abc、bc、b、c、ca、bca。您是否尝试调试代码?@Nitish:std::string::length返回一个无符号的int size\u t,如果字符串为空,最终可能会导致-1下溢。@Nitish在您对上面第二个示例的注释中为什么是重复的?结构化绑定的一个很好的示例。不确定Not代替!的用法@阿德里安迈尔,谢谢。我的眼睛不喜欢!继续:-max+1:你在这里接力一些非常奇怪的事情。你不觉得吗?我会投给你的readability@AdrianMaire我依赖于一个不太奇怪的隐式转换I.m.o。我添加了一个static_断言,以使其更加可见。
#include <limits>
#include <vector>
unsigned count_substr_without_repeating_chars(const std::string& s) {
static_assert(sizeof(char) < sizeof(int),
"not a good solution on this platform");
unsigned r = 0;
for(unsigned f = 0; f < s.size(); ++f) { // first char
std::vector<bool> seen(
// make space for all char:s
std::numeric_limits<unsigned char>::max() + 1
);
for(unsigned l = f; l < s.size(); ++l) { // last char
auto ch = static_cast<unsigned char>(s[l]);
if(seen[ch]) break; // no need to investigate this further
seen[ch] = true;
++r;
}
}
return r;
}