LeetCode 3335: Total Characters in String After Transformations I

Problem Description

Explanation:

To solve this problem, we will iterate through the input string s and apply the given transformations based on the rules provided. We will keep track of the resulting string after each transformation and repeat this process t times. Finally, we will return the length of the resulting string modulo 10^9 + 7.

Algorithmic Idea:

  1. Iterate through each character in the input string s.
  2. Apply the transformation rules:
    • If the character is z, replace it with ab.
    • Otherwise, replace it with the next character in the alphabet.
  3. Repeat this process t times.
  4. Return the length of the resulting string modulo 10^9 + 7.

Time Complexity:

The time complexity of this solution is O(N*T), where N is the length of the input string s and T is the number of transformations.

Space Complexity:

The space complexity of this solution is O(N), where N is the length of the input string s.

:

Solutions

class Solution {
    public int totalCharacters(String s, int t) {
        long result = s.length();
        for (int i = 0; i < t; i++) {
            StringBuilder sb = new StringBuilder();
            for (char c : s.toCharArray()) {
                if (c == 'z') {
                    sb.append("ab");
                } else {
                    sb.append((char)(c + 1));
                }
            }
            s = sb.toString();
            result = s.length();
        }
        return (int)(result % 1000000007);
    }
}

Loading editor...