LeetCode-in-Java

3039. Apply Operations to Make String Empty

Medium

You are given a string s.

Consider performing the following operation until s becomes empty:

For example, let initially s = "aabcbbca". We do the following operations:

Return the value of the string s right before applying the last operation. In the example above, answer is "ba".

Example 1:

Input: s = “aabcbbca”

Output: “ba”

Explanation: Explained in the statement.

Example 2:

Input: s = “abcd”

Output: “abcd”

Explanation: We do the following operation:

The string just before the last operation is “abcd”.

Constraints:

Solution

public class Solution {
    public String lastNonEmptyString(String s) {
        int[] freq = new int[26];
        char[] ar = s.toCharArray();
        int n = ar.length;
        int max = 1;
        StringBuilder sb = new StringBuilder();
        for (char c : ar) {
            freq[c - 'a']++;
            max = Math.max(freq[c - 'a'], max);
        }
        for (int i = n - 1; i >= 0; i--) {
            if (freq[ar[i] - 'a'] == max) {
                sb.append(ar[i]);
                freq[ar[i] - 'a'] = 0;
            }
        }
        return sb.reverse().toString();
    }
}