我想要一个计算唯一字符数的函数。例如,如果我有 aabbcc
,我希望它返回 3
。如果 aab
我想要 2
等等....
我的尝试是构建一个函数来检查之前是否出现过数字,然后将其用作 if
条件。
我的代码是:
bool firstocc(char* t, int i){
for(int j = 0;j < i;j++){
if(t[j] == t[i]) return false;
return true;
}
}
int h(char* t){
int c=0;
for(int i=0; t[i+1]!=0;i++){
if(firstocc(t,i)){
c++;
}
return c;
}
}
int main()
{
cout<< h("aabbc");
}
函数总是返回零。有什么问题吗?
最佳答案
如果你的字符串总是遵循模式,当相同的符号组合在一起时,那么计数就很简单了:
int count_unique( const std::string &str )
{
char last = 0;
int count = 0;
for( char c : str )
if( last != c ) {
last = c;
++count;
}
return count;
}
如果它们不是强制分组使用std::set
:
int count_unique( const std::string &str )
{
return std::set<char>( str.begin(), str.end() ).size();
}
如果 std::set
不被允许并且没有分组则使用第一个稍微修改的:
int count_unique( std::string str )
{
std::sort( str.begin(), str.end() );
char last = 0;
int count = 0;
for( char c : str )
if( last != c ) {
last = c;
++count;
}
return count;
}
关于c++ - 计算数组中唯一字符的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40769816/