LeetCode-in-Java

3223. Minimum Length of String After Operations

Medium

You are given a string s.

You can perform the following process on s any number of times:

Return the minimum length of the final string s that you can achieve.

Example 1:

Input: s = “abaacbcbb”

Output: 5

Explanation:
We do the following operations:

Example 2:

Input: s = “aa”

Output: 2

Explanation:
We cannot perform any operations, so we return the length of the original string.

Constraints:

Solution

public class Solution {
    public int minimumLength(String s) {
        int[] freq = new int[26];
        for (int i = 0; i < 26; i++) {
            freq[i] = 0;
        }
        for (int i = 0; i < s.length(); i++) {
            freq[s.charAt(i) - 'a']++;
        }
        int c = 0;
        for (int i : freq) {
            if (i != 0) {
                if (i % 2 == 0) {
                    c += 2;
                } else {
                    c += 1;
                }
            }
        }
        return c;
    }
}