重新排列字符串中的字符,使得两个相邻的字符不相同

时间:2017-03-24 15:24:11

标签: c++ operator-overloading priority-queue

有人可以解释一下这行代码:

pq.push( Key { count[c-'a'], c} )

重载运算符如何为此代码工作?

为什么我无法更改此特定行

bool operator <(const Key &k) const

指向此特定operator>

bool operator >(const Key &k) const

完整代码如下:

    const int MAX_CHAR = 26;

struct Key
{
    int freq; 
    char ch;
     bool operator <(const Key &k) const
    {
        return freq < k.freq;
    }

};
void rearrangeString(string str)
{
    int n = str.length();
    int count[MAX_CHAR] = {0};
    for (int i = 0 ; i < n ; i++)
    {
        count[str[i]-'a']++;
        cout<<"count "<<str[i]-'a'<<" "<<count[str[i]-'a']<<" "<<endl;
    }
    priority_queue< Key > pq;
    for (char c = 'a' ; c <= 'z' ; c++)
        if (count[c-'a'])
            pq.push( Key { count[c-'a'], c} );

    cout<<endl<<pq.top().ch;
    str = "" ;

    Key prev {-1, '#'} ;
    while (!pq.empty())
    {
        Key k = pq.top();
        pq.pop();
        str = str + k.ch;
        if (prev.freq > 0)
            pq.push(prev);
        (k.freq)--;
        prev = k;
    }
    if (n != str.length())
        cout << " Not valid String " << endl;

    else 
        cout << str << endl;
}
int main()
{
    string str = "bbbaa" ;
    rearrangeString(str);
    return 0;
}

1 个答案:

答案 0 :(得分:3)

Key { count[c-'a'], c}通过将Key初始化为freq并将count[c-'a']初始化为ch来构建c个对象。然后该对象作为参数传递给pq.push调用。

operator >不起作用,因为您是默认比较器使用Key的{​​{1}}中的std::priority_queue。要改为使用<,请像这样声明>

pq