LeetCode-in-Java

3335. Total Characters in String After Transformations I

Medium

You are given a string s and an integer t, representing the number of transformations to perform. In one transformation, every character in s is replaced according to the following rules:

Return the length of the resulting string after exactly t transformations.

Since the answer may be very large, return it modulo 109 + 7.

Example 1:

Input: s = “abcyy”, t = 2

Output: 7

Explanation:

Example 2:

Input: s = “azbk”, t = 1

Output: 5

Explanation:

Constraints:

Solution

import java.util.LinkedList;

public class Solution {
    public int lengthAfterTransformations(String s, int t) {
        int[] count = new int[26];
        for (char c : s.toCharArray()) {
            count[c - 'a']++;
        }
        LinkedList<Integer> list = new LinkedList<>();
        for (int c : count) {
            list.add(c);
        }
        int delta = s.length() % 1000000007;
        for (int i = 0; i < t; i++) {
            int zCount = list.removeLast() % 1000000007;
            int aCount = list.pollFirst() % 1000000007;
            list.offerFirst((aCount + zCount) % 1000000007);
            list.offerFirst(zCount);
            delta = delta % 1000000007;
            delta = (delta + zCount) % 1000000007;
        }
        return delta;
    }
}