fork download
  1. #include<bits/stdtr1c++.h>
  2. using namespace std;
  3. int main()
  4. {
  5. ios_base::sync_with_stdio(false);
  6. cin.tie(NULL);
  7. int n,i=0,c=0;
  8. cin>>n;
  9. string s,fin="";
  10. cin>>s;
  11. while(i<n)
  12. {
  13. if(i+1<n)
  14. {
  15. ///if char at odd and even place is different increase iterator by 2
  16. if(s[i]!=s[i+1])
  17. fin=fin+s[i]+s[i+1],i+=2;
  18. else
  19. {
  20. fin+=s[i];
  21. int j = i+1;
  22. ///if several upcoming char are same then iterate over it . In this case j iterates by 1 and new value of i is alloted as j+1
  23. while(s[i]==s[j] and j<n)
  24. j++,c++;
  25. if(j<n)
  26. fin+=s[j],i=j+1;
  27. else
  28. i=n;
  29.  
  30.  
  31. }
  32. }
  33. else
  34. {
  35. ///for the last character
  36. int x = fin.length();
  37. if(x & 1)
  38. {
  39. if(fin[x-1]!=s[i])
  40. fin+=s[i];
  41. else
  42. c++;
  43. }
  44. else
  45. c++;
  46. i=n;
  47. }
  48. }
  49.  
  50. if(fin.length() & 1)
  51. {
  52. fin.pop_back();
  53. cout << c+1 << endl << fin << endl;
  54. }
  55. else
  56. cout << c << endl << fin << endl;
  57.  
  58. }
  59.  
Success #stdin #stdout 0s 15240KB
stdin
4
aabc
stdout
2
ab