Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- https://practice.geeksforgeeks.org/problems/6a1b365b520f10c8a29b533eb72951b4b4237b57/1
- 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.
- Example 1:
- Input:
- str = "bbaaabb"
- Output:
- 2
- Explanation:
- Operation 1: Removal of all a's modifies str to "bbbb".
- Operation 2: Removal of all remaining b's makes str
- empty.
- Therefore, the minimum number of operations required
- is 2.
- Example 2:
- Input:
- str = "aababaa"
- Output:
- 3
- Explanation:
- Operation 1: Removal of b's modifies str to "aaabaa".
- Operation 2: Removal of b's modifies str = "aaaaa".
- Operation 3: Removal of all remaining a's makes str
- empty.
- Therefore, the minimum number of operations required
- is 3.
- Constraints:
- 1 <= str.length() <= 10^5
- 'a' <= str[i] <= 'b'
- ------------------------------------------------------------------------------------------------------------------------------------
- int minSteps(string str) {
- int counta=0;
- int countb=0;
- for(int i=0;i<str.size();i++){
- int flag=0;
- while(i<str.size() && str[i]=='a'){
- flag=1;
- i++;
- }
- counta+=flag;
- }
- for(int i=0;i<str.size();i++){
- int flag=0;
- while(i<str.size() && str[i]=='b'){
- flag=1;
- i++;
- }
- countb+=flag;
- }
- return min(counta,countb)+1;
- }
Advertisement
Add Comment
Please, Sign In to add comment