koenjazh-CNfresde
짬뽕얼큰하게의 맨땅에 헤딩 :: Minimum Number of Changes to Make Binary String Beautiful

Leetcode Problem:

Summary

  • The problem requires to find the minimum number of changes required to make a binary string beautiful
  • A beautiful string is a string that can be partitioned into substrings with even length and only containing 1's or 0's.

Approach

  • The approach is to iterate over the string in steps of 2 and count the number of pairs of characters that are not the same
  • If the pair is not the same, it means that the string needs to be changed to make it beautiful, so we increment the result.

Complexity

  • O(n/2) = O(n), where n is the length of the string.

Explanation

  • The solution iterates over the string in steps of 2, which is because each pair of characters is considered together
  • If the pair of characters is not the same, it means that the string needs to be changed to make it beautiful, so we increment the result
  • The time complexity is O(n) because we are iterating over the string once.

Solution Code:


class Solution {
public:
    int minChanges(string s) {
        int res = 0;
        for(int i = 0 ; i < s.size(); i += 2){
            if ((s[i] == '0' && s[i+1] == '0') || (s[i] == '1' && s[i+1] == '1')){
                continue;
            }
            res++;
        }
        return res;
    }
};

'알고리즘' 카테고리의 다른 글

Find if Array Can Be Sorted  (0) 2025.02.21
Find Unique Binary String  (0) 2025.02.20
String Compression III  (0) 2025.02.20
Rotate String  (0) 2025.02.20
Delete Characters to Make Fancy String  (0) 2025.02.20
블로그 이미지

짬뽕얼큰하게

,