Problem overview
Version 3 of the tr project copies the -d flag, which deletes characters instead of translating them. trDelete(lines: List<String>, chars: String): String removes from every line each character that appears in chars, then returns the lines joined with \n.
chars is a non-empty ASCII string whose characters are taken literally, and upper and lower case are different characters. A line can become empty after the deletions, and it then stays in the output as an empty line. For ["banana", "apple"] with "aeiou" the result is "bnn\nppl".
Approach
The question to answer for every character of every line is: "is this one of the characters to delete?" Searching chars each time would work, but a HashSet answers membership questions in a single step on average. So the function first turns chars into a set, then goes through each line, keeping only the characters that are not in the set.
The second version of the project used a map for a similar job. Here no replacement is needed, so a set is enough: the only information per character is "delete" or "keep".
Step by step
- Create the set.
val set = HashSet<Char>()will hold the characters to delete. - Fill it. Loop
for (i in 0 until chars.length)over the positions ofchars. - Add each character.
set.add(chars[i]). A set stores each character once, even ifcharsrepeats it. - Prepare the output.
resultis an emptyArrayList<String>. - Loop over the lines with
for (line in lines). - Create a builder per line.
val sb = StringBuilder()will hold the line without the deleted characters. Making a new one for each line keeps the lines from mixing. - Loop over the positions of the line with
for (j in 0 until line.length). - Name the character.
val ch = line[j]makes the next lines easier to read. - Keep it unless it is in the set.
if (!set.contains(ch))is true for characters that stay. The!flips the answer ofcontains. - Append the kept character with
sb.append(ch). Characters in the set are skipped, which is how they are deleted. - Store the line. After the inner loop,
result.add(sb.toString()). This sits outside the inner loop's braces, so it runs once per line, even when the line ended up empty. - Join after the outer loop with
joinToString("\n").
The solution in Kotlin
class Solution {
fun trDelete(lines: List<String>, chars: String): String {
val set = HashSet<Char>()
for (i in 0 until chars.length) {
set.add(chars[i])
}
val result = ArrayList<String>()
for (line in lines) {
val sb = StringBuilder()
for (j in 0 until line.length) {
val ch = line[j]
if (!set.contains(ch)) {
sb.append(ch)
}
}
result.add(sb.toString())
}
return result.joinToString("\n")
}
}
Kotlin details in this code
- Characters are
Char.chars[i]andline[j]giveCharvalues, so the set is aHashSet<Char>. ACharin a string indexes at 0, and0 until line.lengthstops at the last valid index. !set.contains(ch)can also be writtench !in set, which reads more naturally in Kotlin. Both mean the same thing.- Strings can't be edited in place. A Kotlin
Stringis immutable, so you can't remove a character fromline. The code builds a new string in aStringBuilderfrom the characters to keep instead. - A shorter form exists.
Stringhas afiltermethod that keeps the characters for which a condition is true, soline.filter { it !in set }builds the same cleaned line in one expression. It givesbnnfor"banana"with the same set. The lesson's explicit loop and builder show whatfilterdoes underneath. - The loop over positions could be a loop over characters,
for (ch in line), as in the previous version. The lesson uses positions here to practise indexing, and the result is the same.
Tracing the example
For the line "apple" with chars = "aeiou" the set holds a, e, i, o and u. The characters a and e are in the set and are skipped, while p, p and l are not and are appended. The builder ends as ppl. The line "banana" keeps b, n and n, giving bnn, which is why the joined result is "bnn\nppl".
The deleted characters can be anywhere in the line, at the start, in the middle or at the end, and consecutive ones disappear together. The loop needs no special handling for any of these positions.
Complexity
Building the set takes O(m) for a chars string of length m. Each input character is checked once, in constant time on average, so the scan costs O(total characters). The extra space is the set plus the output.
Edge cases and common mistakes
- A line that disappears. With
["aaa", "xyz", "Apple"]and"aeiouA"the result is an empty line, thenxyz, thenppl. The first line must stay in the output as an empty line, which is whyresult.addis called for every line, even when the builder is empty. - Repeated characters in
chars."aaa"works like"a", because the set holds each character once. With["aaa", "xyz"]the result is an empty line andxyz. - Case matters. With
chars = "aeiou", the uppercaseAin"Apple"is kept and the result isAppl. Only when"A"is also incharsdoes it go. - Putting
result.addinside the inner loop. That would store a partly built line after every character instead of one finished line. - Forgetting the
!. Without it the function keeps only the characters it should delete.
