LeetCode in Kotlin

2186. Minimum Number of Steps to Make Two Strings Anagram II

Medium

You are given two strings s and t. In one step, you can append any character to either s or t.

Return the minimum number of steps to make s and t anagrams of each other.

An anagram of a string is a string that contains the same characters with a different (or the same) ordering.

Example 1:

Input: s = “leetcode”, t = “coats

Output: 7

Explanation:

“leetcodeas” and “coatsleede” are now anagrams of each other.

We used a total of 2 + 5 = 7 steps.

It can be shown that there is no way to make them anagrams of each other with less than 7 steps.

Example 2:

Input: s = “night”, t = “thing”

Output: 0

Explanation: The given strings are already anagrams of each other. Thus, we do not need any further steps.

Constraints:

Solution

class Solution {
    fun minSteps(s: String, t: String): Int {
        val a = IntArray(26)
        for (i in 0 until s.length) {
            a[s[i].code - 'a'.code]++
        }
        for (i in 0 until t.length) {
            a[t[i].code - 'a'.code]--
        }
        var sum = 0
        for (j in a) {
            sum += Math.abs(j)
        }
        return sum
    }
}