
Kotlin
Leetcode: Count Items Matching a Rule (Kotlin)
December 26, 2024
Leetcode: Count Items Matching a Rule (Kotlin)
This is an easy array problem on Leetcode. Count Items Matching a Rule - LeetCode
Problem Statement
Examples
Constraints
Understanding the Problem
You should use the given rule key to determine which index in each list you should check (“type” == 0, “color” == 1, “name == 2” . You will then check the value at the index in each list to the given rule value. You count each time these values match.
Approach #1
The first way I solved this was by using a map that had a string as the key and the values as integers. This way, I could use the given rule key to get the given rule index. Then I loop through each list to find matches. I then returned the number of matches.
class Solution {
fun countMatches(items: List<List<String>>, ruleKey: String, ruleValue: String): Int {
val map = mutableMapOf(
"type" to 0,
"color" to 1,
"name" to 2
)
val indexToMatch = map[ruleKey]
var matches = 0
for(list in items){
indexToMatch?.let{ index->
if(list[index] == ruleValue) matches++
}
}
return matches
}
}
Approach #2:
Approach number 2 would use a when statement and assign that to an immutable value.
class Solution {
fun countMatches(items: List<List<String>>, ruleKey: String, ruleValue: String): Int {
val indexToMatch = when(ruleKey){
"type" -> 0
"color" -> 1
else -> 2
}
var matches = 0
for(list in items){
if(list[indexToMatch] == ruleValue) matches++
}
return matches
}
}