RainX_69

Minimum steps to reduce string to empty by deleting consecutives | OA | TRICKY

May 9th, 2023 (edited)
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.44 KB | Source Code | 0 0
  1. https://practice.geeksforgeeks.org/problems/6a1b365b520f10c8a29b533eb72951b4b4237b57/1
  2.  
  3. Given a string str consisting of only two characters 'a' and 'b'. You need to find the minimum steps required to make the string empty by removing consecutive a's and b's.
  4.  
  5. Example 1:
  6. Input:
  7. str = "bbaaabb"
  8. Output:
  9. 2
  10. Explanation:
  11. Operation 1: Removal of all a's modifies str to "bbbb".
  12. Operation 2: Removal of all remaining b's makes str
  13. empty.
  14. Therefore, the minimum number of operations required
  15. is 2.
  16.  
  17. Example 2:
  18. Input:
  19. str = "aababaa"
  20. Output:
  21. 3
  22. Explanation:
  23. Operation 1: Removal of b's modifies str to "aaabaa".
  24. Operation 2: Removal of b's modifies str = "aaaaa".
  25. Operation 3: Removal of all remaining a's makes str
  26. empty.
  27. Therefore, the minimum number of operations required
  28. is 3.
  29.  
  30. Constraints:
  31. 1 <= str.length() <= 10^5
  32. 'a' <= str[i] <= 'b'
  33.  
  34. ------------------------------------------------------------------------------------------------------------------------------------
  35. int minSteps(string str) {
  36.    int counta=0;
  37.    int countb=0;
  38.    for(int i=0;i<str.size();i++){
  39.        int flag=0;
  40.        while(i<str.size() && str[i]=='a'){
  41.            flag=1;
  42.            i++;
  43.        }
  44.        counta+=flag;
  45.    }
  46.    for(int i=0;i<str.size();i++){
  47.        int flag=0;
  48.        while(i<str.size() && str[i]=='b'){
  49.            flag=1;
  50.            i++;
  51.        }
  52.        countb+=flag;
  53.    }
  54.    return min(counta,countb)+1;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment