Overview
What You’ll Learn
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.
Also, check out this video tutorial on implementing these solutions:
Brainstorm and solve
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 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
}
Congratulations
Congratulations, we have went through a couple of ways to solve Leetcode - Valid Anagram (Kotlin)!
Also, check out the video tutorial on implementing these solutions: