Antony Ajay
Antony Ajay

Reputation: 83

Pattern matching

I was just wondering if any other logic is possible for this problem: Question : Find the number of pairs in a given string and output the sum of all the pairs and the unpaired elements. PS: The input is case sensitive.

Example O/P:

eeqe 3

aaaa 2

rwertr 5

I figured out the solution to this problem by first sorting the input string and then comparing adjacent elements as shown in the code below:

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;

}

This code works fine. But, I was just wondering if there is any other efficient solution to this problem that doesn't involve sorting the entire input array.

Upvotes: 1

Views: 1797

Answers (1)

ipc
ipc

Reputation: 8143

It basically avoids sorting based on the idea that there are only 256 possible chars, so it's sufficent to count them.This is my solution:

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

If, for example, the string contains 5 times an 'a', this allows 5/2 pairs (integer division) and 1 remains unpaired (because 5 is odd => 5%2 is 1)

Edit: Because we are here in SO:

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

Upvotes: 1

Related Questions