我只是想知道是否有其他逻辑可以解决这个问题:问题:找到给定字符串中的配对数量,并输出所有配对和未配对元素的总和。PS:输入区分大小写。
示例O/P:
eeqe 3
aaaa 2
rwertr 5
通过首先对输入字符串进行排序,然后比较相邻元素,我找到了这个问题的解决方案,如下面的代码所示:
int main()
{
int t,count=0,pos=0;
char swap;
char a[201];
cin>>a;
int len=strlen(a);
//cout<<a<<endl;
for (int c = 0 ; c < ( len - 1 ); c++)
{
for (int d = 0 ; d < len - c - 1; d++)
{
if (a[d] > a[d+1]) /* For decreasing order use < */
{
swap = a[d];
a[d] = a[d+1];
a[d+1] = swap;
}
}
}
//cout<<a<<endl;
count=0;
for(int i=0;i<len;){
if(a[i]==a[i+1]){
count++;
i+=2;
//if(i== len-2)i++;
}
else{ count++; i++;}
}
//if(a[len-1]!=a[len-2])count++;
cout<<count<<endl;
return 0;}
这段代码运行良好。但是,我想知道是否有任何其他有效的解决方案来解决这个问题,而不涉及对整个输入数组进行排序。
发布于 2013-02-03 08:44:46
它基本上避免了基于只有256个可能字符的想法进行排序,所以我的解决方案是计算them.This就足够了:
int main()
{
std::string s; std::cin >> s;
int cnt[256] = {};
for (std::size_t i = 0; i < s.size(); ++i)
++cnt[static_cast<unsigned char>(s[i])];
int sum = 0;
for (std::size_t i = 0; i < 256; ++i)
sum += cnt[i]/2 + cnt[i]%2;
std::cout << sum << std::endl;
}编辑:因为我们在这里,所以:
int main()
{
std::array<int, 256> cnt{-1}; // last char will be '\0', ignore this.
std::for_each(std::istreambuf_iterator<char>(std::cin.rdbuf()),
std::istreambuf_iterator<char>{},
[&](unsigned char c){++cnt[c];});
std::cout << std::accumulate(cnt.begin(), cnt.end(), 0,
[](int i, int c)->int{return i+(c/2)+(c%2);}) << '\n';
}https://stackoverflow.com/questions/14668222
复制相似问题