Problem overview
The third version of the tr tool behaves like tr -d. The method trDelete(List<String> lines, String chars) removes from every line each character that appears in chars, then returns the lines joined by \n.
chars is a non-empty ASCII string whose characters are literal: no ranges. Upper and lower case are different characters. A line can become empty after the deletion, and then it stays in the output as an empty line.
For ["banana", "apple"] and chars = "aeiou", the answer is "bnn\nppl". Printed, that is bnn and ppl.
Approach: keep a character only if it isn't in the set
Instead of deleting from a string, which Java can't do because strings are immutable, build each cleaned line from the characters that survive. A character survives when it isn't one of the characters to delete.
That test runs once for every character of every line, so it should be quick. A Set<Character> answers "is this character a member?" in constant time on average. Searching the string chars would also work, but it scans the string each time. Filling the set takes one pass over chars, and a set keeps each character once, however often it appears in chars.
For each line, a StringBuilder collects the kept characters, and toString() turns it back into a String that goes into a result list. The list is joined at the end.
Here is "banana" with chars = "aeiou", showing the builder after each character:
j=0 ch=b sb=b
j=1 ch=a sb=b
j=2 ch=n sb=bn
j=3 ch=a sb=bn
j=4 ch=n sb=bnn
j=5 ch=a sb=bnn
The builder only grows on characters that aren't in the set. Each a is looked at and ignored, and the final bnn is what goes into the result.
Deleting characters with a regular expression, such as replaceAll, is a trap for this task. A pattern gives special meaning to characters like ., [ and ], and the lesson wants every character taken literally. The set-based loop never interprets anything.
The set is built once, before the loop over the lines, because it depends only on chars. Building it inside the line loop would repeat the same work for every line and give the same answer each time.
Step by step
- Create
set, aSet<Character>set to a newHashSet. It holds the characters to delete. - Loop over the positions of
charswithifrom 0 tochars.length() - 1. - Add each character with
set.add(chars.charAt(i)). - Create
result, an empty list of strings for the cleaned lines. - Loop over the lines with a for-each loop that names each element
line. - Create a fresh
StringBuildernamedsbfor each line. - Loop over the positions of
linewithjfrom 0 toline.length() - 1. - Read the character at position
jinto acharnamedch. - Test for a keeper.
!set.contains(ch)is true when the character isn't in the set. The!flips the answer ofcontains. - Append
chtosbinside thatif. Characters in the set are simply never appended, which is how they get deleted. - After the inner loop, add
sb.toString()toresult. This runs once per line, so it sits outside the inner loop's braces. A line that lost every character is added as an empty string. - After the outer loop, return
String.join("\n", result).
The solution in Java
class Solution {
public String trDelete(List<String> lines, String chars) {
Set<Character> set = new HashSet<>();
for (int i = 0; i < chars.length(); i++) {
set.add(chars.charAt(i));
}
List<String> result = new ArrayList<>();
for (String line : lines) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < line.length(); j++) {
char ch = line.charAt(j);
if (!set.contains(ch)) {
sb.append(ch);
}
}
result.add(sb.toString());
}
return String.join("\n", result);
}
}
Details worth knowing:
- Autoboxing. The set holds
Characterobjects, whilecharAtreturns a primitivechar. Java converts automatically inset.add(...)andset.contains(ch). addignores duplicates. Forchars = "aab"the set has two elements. No check is needed in the loop.- A
StringBuilderper line. Declaring it inside the for-each loop gives every line a fresh, empty builder. Declared outside, it would carry the previous lines along. - Imports.
List,ArrayList,SetandHashSetare injava.util.
Complexity
Time: O(m + t), where m is the length of chars and t is the total number of characters in all lines. Building the set takes m additions, and each character of the text costs one membership test, which is constant on average.
Space: O(m + t). The set holds at most m characters, and the builders and the result hold the cleaned text.
Edge cases and common mistakes
- Lines that become empty.
["aaa", "bob"]with"ab"gives"\no": the first line is empty and is still a line. Skipping empty results would shift every later line up. - Empty lines in the input.
["a", "", "b"]with"a"gives"\n\nb": two empty lines, thenb. - Case.
["Hello, World!"]with"lo"gives"He, Wrd!". The capitalWand the capitalHare not in the set, and every lowercaselandois gone. - Punctuation is just characters. Commas, spaces and exclamation marks are kept unless they are in
chars. - Repeated characters in
chars.["aab"]with"aa"gives"b", the same as with"a". - Using
containswithout!. That keeps only the characters to delete and throws the rest away.
Testing
["banana", "apple"]with"aeiou"gives"bnn\nppl".["aaa", "bob"]with"ab"gives"\no".["Hello, World!"]with"lo"gives"He, Wrd!".["a", "", "b"]with"a"gives"\n\nb".
