Problem overview
This version of TrSqueeze imitates tr -s. It takes a List<string> of lines and a non-empty string chars. In each line, every run of the same character that appears in chars collapses to one occurrence. All other characters, and runs of characters that are not in chars, stay as they are. The lines are returned joined with "\n". Case matters, and lines may be empty.
For ["aaabbb", "abaa"] with chars = "a", the result is "abbb\naba". The three as become one, and the bs are not in chars, so they stay. In "abaa" the first a is alone and the last two collapse to one.
Approach: skip a character that repeats the one just kept
A character is dropped when two things are both true: it is one of the characters to squeeze, and it is equal to the character kept just before it. Everything else is appended. So the method needs two things for each line:
- a
HashSet<char>of the squeezable characters, built once; - a variable
prevfor the last character that went into the output.
Comparing with the previous kept character is what limits the squeeze to runs of the same character. In "aabb" with chars = "ab", the second a equals prev and is skipped. The first b differs from prev (a), so it is kept, and the second b is then skipped. The result is "ab", not "a".
Trace "aaabbb" with chars = "a". The first a is in the set, but prev is '\0', so it is kept and prev becomes a. The second and third a are in the set and equal prev, so both are skipped. Each b is not in the set, so the first part of the test is false, and all three are kept. The builder holds "abbb".
Step by step
- Create
squeeze, an emptyHashSet<char>. - Loop over the positions of
charswithi. - Add
chars[i]to the set. - Create
result, an emptyList<string>. - Write a
foreachloop overlineswith the variableline. - Create a
StringBuilder sbfor this line. - Create
char prev = '\0', the null character. At the start of a line nothing has been kept, soprevstarts as a value that is not expected in a line. - Loop over the characters of
linewithj. - Read the character at position
jintochar ch. - Test
squeeze.Contains(ch) && ch == prev. The character is skipped only when both parts hold. - Write
continueinside theif. It jumps to the next character, so this one is never appended. - Append
chtosbafter theif. The first character of a run is kept, and only the repeats after it are dropped. - Set
prev = ch.prevalways holds the last kept character, so the next character is compared with it. - After the inner loop, add
sb.ToString()toresult. - After the outer loop, return
string.Join("\n", result).
The solution in C#
class Solution {
public string TrSqueeze(List<string> lines, string chars) {
HashSet<char> squeeze = new HashSet<char>();
for (int i = 0; i < chars.Length; i++) {
squeeze.Add(chars[i]);
}
List<string> result = new List<string>();
foreach (string line in lines) {
StringBuilder sb = new StringBuilder();
char prev = '\0';
for (int j = 0; j < line.Length; j++) {
char ch = line[j];
if (squeeze.Contains(ch) && ch == prev) {
continue;
}
sb.Append(ch);
prev = ch;
}
result.Add(sb.ToString());
}
return string.Join("\n", result);
}
}
The C# details:
'\0'is acharliteral for the character with code 0. It is a placeholder here, since ordinary text doesn't contain it.&&short-circuits. Ifsqueeze.Contains(ch)is false, the comparison withprevisn't evaluated, and the character is appended.continueapplies to the innermost loop. Here that is the loop overj, so the next character of the same line is processed. The outerforeachis unaffected.previs declared inside theforeach, so every line starts with a fresh'\0'. A character at the start of one line can't be treated as a repeat of the end of the previous line.- Chars are values.
ch == prevcompares the two characters by code, so'a'and'A'are not equal.
The method never looks ahead and never needs to remember more than one character. That is what keeps the work to a single pass over each line: the decision for each character depends only on the character itself and on the last one kept.
Complexity
Let k be the length of chars and L the total number of characters in all lines. Time: O(k + L), since each character costs one set lookup and one comparison. Space: O(k + L) for the set, the builders and the output.
Edge cases and common mistakes
- Different characters in a row.
["aabbcc"]with"ab"gives"abcc". Thecs are not inchars, so they stay doubled. - Alternating characters.
["abab"]with"ab"stays"abab", because no character repeats the one right before it. - Case.
["aAaa"]with"ab"gives"aAa": only the last two lowercaseas are a run. - Spaces.
charsmay be a space.["", " x y"]with" "gives"\n x y": the empty line stays, and each run of spaces becomes one. - Several squeezed characters.
["mississippi"]with"sp"gives"misisipi". - Checking only
ch == prev. Without the set test, every repeated character would collapse, including thebs in"aaabbb", which the lesson keeps. - Checking only the set. Without the
prevtest, every squeezable character would be dropped, which is deletion, not squeezing:"abaa"with"a"would become"b"instead of"aba".
Testing
["aaabbb", "abaa"],"a"gives"abbb\naba".["aabbcc"],"ab"gives"abcc".["abab"],"ab"gives"abab".["mississippi"],"sp"gives"misisipi".
