I will show you my approach to solving the Leetcode easy problem, Valid Anagram, using Kotlin. The problem statement is: Given two strings s and t, return true if t is an anagram of s, and false otherwise. They also give two examples shown below:
Basically, a valid anagram of another string consists of a string that contains the same characters and the same count of each character. Anytime you need to keep a count of something, using a hashmap can be considered. This is the approach I took in solving this problem.
These are the steps I took in solving this:
Compare the size of both strings. If they are not equal, we do not need to do anything else and can return false.
Create a HashMap with Char keys and Int values.
Create character arrays of both strings.
Loop through one of the character arrays and add the count of each character to the HashMap.
Loop through the other character array and check if each character is in the HashMap. Decrement the count if the character is found and the count is bigger than 0. If the count is 0, return false since there is a higher count of this character.
After you go through checking if every character in the second character array is in the map, this means both strings are valid anagrams.
Check out the code below:
fun isAnagram(s: String, t: String): Boolean {
if(s.length != t.length) return false
val map = HashMap<Char, Int>()
val sArray = s.toCharArray()
val tArray = t.toCharArray()
for(c in sArray) map[c] = map.getOrDefault(c, 0) + 1
for(c in tArray){
var current = map.getOrDefault(c, 0)
if(current < 1) return false
map[c] = --current
}
return true
}
Check out the codelab version of this solution:
https://cmcoffeedev.com/codelabs/leetcode-valid-anagram/index.html
Check out the video version of this solution here:
Top comments (0)