Problem overview
The tr project rebuilds the Unix command that translates characters. In version 1, tr(lines: Array[String], fromChar: String, toChar: String): String replaces every occurrence of fromChar with toChar in each line and returns the lines joined by \n.
Both characters are single ASCII characters, taken literally: no escapes and no ranges. Upper and lower case are different characters. A line may be empty, and it may not contain fromChar at all. With ["banana", "apple"], fromChar = "a" and toChar = "X", the answer is "bXnXnX\nXpple".
Approach
Each line can be translated on its own, so the plan is a loop: translate a line, collect the result, and join everything at the end. The translation itself needs no loop over characters, because String.replace already replaces every occurrence of one piece of text with another.
Note that fromChar and toChar are declared as String, not Char. That suits replace, which takes two strings in this form.
You could also walk through each line character by character, build a new string and swap the matching characters yourself. That works, but it is more code for the same effect. For a single pair of characters, one call to replace is the simplest correct answer.
Step by step
- Create
result, an emptyscala.collection.mutable.ArrayBuffer[String], in aval. It is a list that grows, and since you only add to it,valis enough. - Write a
forloop withline <- lines. Herelineis a whole line of text, not a single character. - Inside the loop, append
line.replace(fromChar, toChar)toresultwith+=. - After the loop, return
result.mkString("\n"). The separator goes only between lines, so the output has no newline at the end.
The solution in Scala
class Solution {
def tr(lines: Array[String], fromChar: String, toChar: String): String = {
val result = scala.collection.mutable.ArrayBuffer[String]()
for (line <- lines) {
result += line.replace(fromChar, toChar)
}
return result.mkString("\n")
}
}
Details worth knowing:
replacechanges every occurrence, not only the first, and it returns a new string. Strings can't be modified in place, so afterval t = line.replace("a", "X")withline = "banana",lineis stillbananaandtisbXnXnX.replacetakes its arguments literally. The call"a.b.c".replace(".", "-")givesa-b-c. The similar methodreplaceAlltreats its first argument as a regular expression, where.means "any character":"a.b.c".replaceAll(".", "-")gives-----. Since this lesson takes characters literally,replaceis the right one.- Matching is case-sensitive: replacing
"a"in"Apple"leaves the capitalAalone. - The
for (line <- lines)form loops over the elements themselves, with no index to manage.
Complexity
If the lines have a total of N characters, the work is O(N): replace scans each line once, and mkString copies each once. The buffer and the final string need O(N) space.
Edge cases and common mistakes
- Lines without the character.
replacereturns the line unchanged, so["hello"]with"z"and"y"gives"hello". - Empty lines. They stay empty:
["", "abc", ""]with"a"and"z"gives"\nzbc\n", with the empty lines kept at both ends. - Case.
["Apple", "apple"]with"a"and"X"gives"Apple\nXpple". - The regex trap.
replaceAllwith a special character such as.gives surprising results, as shown above. - Joining inside the loop. Adding a
"\n"after every line leaves a newline at the end.mkStringavoids that. - Empty array. The result is
"".
Testing
Inputs worth trying in the editor above, with the result of this solution and the newline shown as \n:
| lines | fromChar, toChar | result |
|---|---|---|
["banana", "apple"] | "a", "X" | "bXnXnX\nXpple" |
["a.b.c", "x"] | ".", "-" | "a-b-c\nx" |
["Apple", "apple"] | "a", "X" | "Apple\nXpple" |
["", "abc", ""] | "a", "z" | "\nzbc\n" |
[] | "a", "b" | "" |
