Problem overview
Version 3 of the tr project behaves like tr -d. The method trDelete(lines: Array[String], chars: String): String removes from every line each character that appears in chars, then returns the lines joined by \n.
chars is a non-empty ASCII string, taken literally with no ranges, and case matters. A line may become empty after the deletion, and then it stays in the output as an empty line. With ["banana", "apple"] and chars = "aeiou", the answer is "bnn\nppl".
Approach
For every character of every line, you have to answer one question: is it one of the characters to delete? A set answers it quickly. Put the characters of chars in a HashSet[Char], then copy into a new string only the characters that are not in the set.
A set also removes duplicates for free: with chars = "aa", the set still holds a once. A plain loop that searched chars for every character would work too, but the set makes each check cost constant time on average.
Step by step
- Create
set, a mutableHashSet[Char], in aval. - Loop over every position
iin0 until chars.length. - In the loop, add
chars(i)to the set withset.add. - Create
result, an emptyArrayBuffer[String], for the cleaned lines. - Loop over each
lineinlines. - Create a fresh
StringBuildernamedsbfor this line. - Loop over every position
jin0 until line.length. - Put the character
line(j)in aval ch. - Write
if (!set.contains(ch)). The!flips the answer, because a character is kept only when it is not in the set. - Inside the
if, appendchtosb. Characters in the set are skipped, which is how they are deleted. - After the inner loop, add
sb.toString()toresult. A line can be empty here, and it is still added. - After the outer loop, return
result.mkString("\n").
The solution in Scala
class Solution {
def trDelete(lines: Array[String], chars: String): String = {
val set = scala.collection.mutable.HashSet[Char]()
for (i <- 0 until chars.length) {
set.add(chars(i))
}
val result = scala.collection.mutable.ArrayBuffer[String]()
for (line <- lines) {
val sb = new StringBuilder()
for (j <- 0 until line.length) {
val ch = line(j)
if (!set.contains(ch)) {
sb.append(ch)
}
}
result += sb.toString()
}
return result.mkString("\n")
}
}
Details to notice:
set.add(x)on a mutable set adds the element and returns aBoolean:trueif it was new,falseif it was already there. Adding'a'twice givestruethenfalse, and the set's size stays 1.set.contains(ch)is the membership test. Indexing a string withline(j)gives aChar, which matches the set's element type.- The deleted characters are never copied. The loop does not edit
line; strings are immutable, so you build a new one insb. - The
StringBuilderis created inside the outer loop. If it were created before the loop, every line would be appended to the same builder, and the lines would run together.
Tracing the example
For the line "banana" with chars = "aeiou", the set holds the five vowels. Here is what the inner loop does for each character:
| ch | kept | sb afterwards |
|---|---|---|
b | yes | b |
a | no | b |
n | yes | bn |
a | no | bn |
n | yes | bnn |
a | no | bnn |
The line becomes "bnn". The second line, "apple", loses its two vowels in the same way and becomes "ppl", so the joined answer is "bnn\nppl".
The same idea can be written with string methods. With val set = "aeiou".toSet, the call "banana".filter(c => !set.contains(c)) gives bnn, and "apple".filterNot(set) gives ppl, because a set can be used as a yes-or-no function on its elements. The loops in the solution do exactly what these calls do, one character at a time, so you can see where the decision happens: at the if, with a check against the set.
The choice of a set matters for longer inputs. Scanning chars from start to end for every character would cost O(k) per check, while a hash set does the same check in constant time on average. For a short chars such as "aeiou" the difference is tiny, and the set mostly makes the intent clear.
Joining deserves a last look. Because mkString("\n") puts the separator only between elements, the number of newline characters in the output is always one fewer than the number of lines, whatever the lines hold. Empty lines are elements like any other, which is why ["aaa", "bob", "aea"] with "ae" keeps its blank first and last lines.
Complexity
Filling the set takes O(k) for k characters in chars. Cleaning takes O(N) for N characters over all lines, because each membership check is O(1) on average. The set uses O(k) space, and the output uses O(N).
Edge cases and common mistakes
- A line that becomes empty.
["aaa", "bob", "aea"]with"ae"gives"\nbob\n". The first and last lines are empty but still present, so the output starts and ends with a newline. - Case.
["Banana"]with"b"gives"Banana": the capitalBis a different character. - Spaces.
["a b c"]with" "gives"abc". A space is an ordinary character here. - Repeated characters in
chars.["hello"]with"ll"gives"heo"; both l characters are removed, and the repeatedlincharsis harmless. - Dropping empty results. Skipping a line that is empty after cleaning would shift the output; the lesson wants it kept.
- Empty array. The result is
"".
