Problem overview
This version of TrDelete imitates tr -d. It takes a List<string> of lines and a non-empty string chars, removes every character that appears in chars from each line, and returns the lines joined with "\n". Characters are literal, and case matters. A line that becomes empty stays in the output as an empty line.
For ["banana", "apple"] with chars = "aeiou", the vowels disappear and the result is "bnn\nppl".
Approach: a set of banned characters, a filter per line
For each character of a line the method asks one question: is it one of the characters to delete? A HashSet<char> answers that quickly. The method fills the set once from chars, then copies a line character by character into a StringBuilder, skipping the characters that are in the set. The builder's text is the cleaned line.
Each line gets its own builder, so cleaned lines never mix, and the empty-line rule needs no code: a builder that received nothing produces "", which goes into the result like any other line.
Trace the word "banana" with the set {a, e, i, o, u}. b is not in the set, so it is appended. a is in the set and is skipped. n is appended, a skipped, n appended, a skipped. The builder holds "bnn".
Two other designs are possible. You could call line.Replace once for each character in chars, replacing it with an empty string. That works for deletion, because removing one character never creates a match for another, but it builds a new string per character. Or you could test membership with chars.Contains(ch) and skip the set. That is simpler, but it scans chars for every character of every line. The set trades a short set-up loop for lookups that don't depend on the length of chars.
Step by step
- Create
set, an emptyHashSet<char>. - Loop over the positions of
charswithiwhilei < chars.Length. - Add
chars[i]to the set. A set stores each character once, so a repeated character incharsdoes no harm. - Create
result, an emptyList<string>. - Write a
foreachloop overlineswith the variableline. - Create a
StringBuilder sbfor the current line. - Loop over the characters of
linewithjwhilej < line.Length. - Read the character at position
jintochar ch. - Test
!set.Contains(ch). A character is kept only when it is not in the set, and!flips the answer. - Append
chtosbinside thatif. Characters in the set are skipped, which is how they get deleted. - After the inner loop, add
sb.ToString()toresult, once per line. - After the outer loop, return
string.Join("\n", result).
The solution in C#
class Solution {
public string TrDelete(List<string> lines, string chars) {
HashSet<char> set = new HashSet<char>();
for (int i = 0; i < chars.Length; i++) {
set.Add(chars[i]);
}
List<string> result = new List<string>();
foreach (string line in lines) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < line.Length; j++) {
char ch = line[j];
if (!set.Contains(ch)) {
sb.Append(ch);
}
}
result.Add(sb.ToString());
}
return string.Join("\n", result);
}
}
The C# details:
HashSet<T>membership is fast.Containstakes constant time on average, no matter how many characters are in the set.Addon a value that is already present just returnsfalseand leaves the set unchanged, with no exception.- Strings can't be edited in place. You can read
line[j], but you can't remove a character fromline. Building a new string is the only way, andStringBuildermakes that cheap, because it appends to an internal buffer instead of creating a new string for every+. charcompares by code.'a'and'A'are different values, so the set deletes only the case you listed.setis an ordinary variable name here. It is only special inside a property definition.
One more point: the lines are processed independently, and the output has exactly as many lines as the input. Deleting characters can shorten a line, but it never removes a line, so the number of newline separators in the result is always one less than the number of lines (or the result is "" for an empty list).
Complexity
Let k be the length of chars and L the total number of characters in all lines. Time: O(k + L), since the set is built in k steps and each character gets one constant-time lookup. Space: O(k + L) for the set, the builders and the output.
Edge cases and common mistakes
- A line that empties out.
["x", "aa", "y"]withchars = "a"gives"x\n\ny". The middle line is empty but still takes its place. Skipping empty results would shift the later lines up. - Everything deleted.
["aaa", "bob"]with"ab"gives"\no". - Case.
["Banana"]with"a"gives"Bnn": the capitalBis untouched, and the lowercaseas are gone. A capitalAwould stay. - Repeated characters in
chars."aa"behaves like"a", thanks to the set. - Putting the
result.Addinside the inner loop. That would add the partly built line once per character. - Reusing one
StringBuilderfor all lines. The lines would pile up into one long string.
Testing
["banana", "apple"],"aeiou"gives"bnn\nppl".["x", "aa", "y"],"a"gives"x\n\ny".["Banana"],"a"gives"Bnn".[],"a"gives"".
