
Sponsored
Sponsored
In this method, we need to count the frequency of each character in strings s and t. We then calculate the number of changes required in t by comparing these frequencies. Specifically, for each character, if the frequency count in s is greater than in t, those are the extra characters needed in t. The total number of these extra characters across all characters gives the result.
Time Complexity: O(n), where n is the length of the strings (since they are of equal length).
Space Complexity: O(1), since the space required does not depend on the input size.
1public class Solution {
2 public int minSteps(String s, String t) {
3 int[] count = new int[26];
4 int steps = 0;
5
6 for (char c : s.toCharArray()) {
7 count[c - 'a']++;
8 }
9
10 for (char c : t.toCharArray()) {
11 count[c - 'a']--;
12 }
13
14 for (int freq : count) {
15 if (freq > 0) {
16 steps += freq;
17 }
18 }
19
20 return steps;
21 }
22
23 public static void main(String[] args) {
24 Solution sol = new Solution();
25 System.out.println(sol.minSteps("leetcode", "practice"));
26 }
27}The Java implementation employs similar logic using an integer array for character counting, with methods for converting characters and accumulating necessary changes.