【问题标题】:Function that counts unique characters in an array计算数组中唯一字符的函数
【发布时间】:2017-04-07 18:41:09
【问题描述】:

我想要一个计算唯一字符数的函数。例如,如果我有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");
}

函数总是返回零。它有什么问题?

【问题讨论】:

  • 调试器是解决此类问题的正确工具。 询问 Stack Overflow 之前,您应该逐行浏览您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。至少,您应该 [编辑] 您的问题,以包含一个重现您的问题的 Minimal, Complete, and Verifiable 示例,以及您在调试器中所做的观察。
  • 您是否尝试过使用调试器?
  • 我已经尝试了你所说的一切,但我仍然无法解决我的问题。这就是我决定写在这里的原因
  • 如果输入总是这样aabbbccc那么你不需要扫描,当符号改变时计数。如果要传递字符串文字,参数必须是 const char * 而不是 char *
  • 输入也可以是 11aab。

标签: c++ function loops boolean


【解决方案1】:

问题在于 firstocch 两个函数中的大括号(可能是因为缩进不好,请务必注意正确缩进代码,不是为了编译器,而是为了你自己),以及函数循环h,其中条件为 t[i+1] != 0,应为 t[i] != 0(包括最后一个字符)。

代码应该是:

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]!=0;i++)
        if(firstocc(t,i)){
            c++;
        }
    return c;
}

我使用"aabbcddddeaa" 对其进行了测试,它返回 5。

【讨论】:

  • 看起来我们得到了相同的答案!
【解决方案2】:

您需要在“c++”行之后添加一个额外的右大括号。

然后在'return c;'之后立即删除多余的大括号

顶部还有一些不平衡的括号。我认为您的代码的工作版本是这样的:

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]!=0;i++){
        if(firstocc(t,i)){
            c++;
        }
    }
    return c;
}

int main(int argc, char *argv[]) {
    std::cout<< h("aac") <<std::endl;
    return 0;
}

【讨论】:

  • 还是错了,我无法收到正确的答案。例如如果我有 "aabbc" 它返回 2 而它应该返回 3
  • 感谢 :)
【解决方案3】:

如果您的字符串始终遵循模式,当相同的符号组合在一起时,计数很简单:

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;
}

【讨论】:

  • 但如果不是,是否可以不使用 std::set ?
猜你喜欢
  • 2021-03-19
  • 1970-01-01
  • 1970-01-01
  • 2016-07-08
  • 1970-01-01
  • 2014-07-08
  • 1970-01-01
  • 2019-04-16
相关资源
最近更新 更多