Problem overview
The fourth version of the tr tool behaves like tr -s. The method trSqueeze(List<String> lines, String chars) collapses each run of the same character into a single occurrence, but only for characters that appear in chars. Everything else is left alone. The lines are joined by \n.
chars is a non-empty ASCII string whose characters are literal: no ranges. Only runs of the same character from chars are collapsed. Other characters, and runs of characters not in chars, stay as they are. Case matters, and lines may be empty.
For ["aaabbb", "abaa"] and chars = "a", the answer is "abbb\naba". The run aaa becomes a, but bbb stays because b is not in chars.
Approach: skip a character that repeats the one just before it
Walk through the line one character at a time and build the output. A character is dropped only when two things are true: it belongs to the squeeze set, and it is the same as the last character that was kept. Then the first character of every run is kept, and the repeats after it are skipped.
Keeping track of the last kept character is enough, because a dropped character equals the kept one before it, so nothing is lost. The variable prev holds it. At the start of each line nothing came before, so prev starts as '\0', the null character, which isn't in a line of ordinary text.
The membership test uses a Set<Character> built once from chars, so each check is constant on average.
Here is "aaabbb" with chars = "a", one character at a time:
a kept -> a
a skipped
a skipped
b kept -> ab
b kept -> abb
b kept -> abbb
The b characters are kept every time. They repeat each other, but b isn't in the set.
Step by step
- Create
squeeze, aSet<Character>set to a newHashSet, for the characters to squeeze. - Loop over the positions of
charswithifrom 0 tochars.length() - 1. - Add each character with
squeeze.add(chars.charAt(i)). - Create
result, an empty list of strings for the squeezed lines. - Loop over the lines with a for-each loop that names each element
line. - Create a fresh
StringBuildernamedsbfor the characters this line keeps. - Create
prevas'\0', the last character that went intosb. It is reset for every line, so a run never continues across a line break. - Loop over the positions of
linewithjfrom 0 toline.length() - 1. - Read the character at position
jinto acharnamedch. - Test for a squeezable repeat:
squeeze.contains(ch) && ch == prev. Both parts must hold. - Skip it with
continue. It jumps to the next character, so this one is never appended andprevstays as it is. - Append
chtosbwhen the test failed. - Set
prevtoch, so the next character is compared with the last one kept. - After the inner loop, add
sb.toString()toresult. A line can end up empty, and it stays in the output as an empty line. - After the outer loop, return
String.join("\n", result).
The solution in Java
class Solution {
public String trSqueeze(List<String> lines, String chars) {
Set<Character> squeeze = new HashSet<>();
for (int i = 0; i < chars.length(); i++) {
squeeze.add(chars.charAt(i));
}
List<String> result = new ArrayList<>();
for (String line : lines) {
StringBuilder sb = new StringBuilder();
char prev = '\0';
for (int j = 0; j < line.length(); j++) {
char ch = line.charAt(j);
if (squeeze.contains(ch) && ch == prev) {
continue;
}
sb.append(ch);
prev = ch;
}
result.add(sb.toString());
}
return String.join("\n", result);
}
}
Details worth knowing:
charcompares with==.ch == prevcompares two primitive characters, which is correct. The set holdsCharacterobjects, butsqueeze.contains(ch)boxes the primitive for you.continueversusbreak.continueends only the current pass of the inner loop, so the next character is still processed.breakwould leave the loop and cut the line short.- The single quotes make a
char.'\0'is one character, whereas"\0"would be aString. - 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. Each character of the text costs one set lookup and one comparison.
Space: O(m + t). The set holds at most m characters, and the builders and the result hold the squeezed text.
Edge cases and common mistakes
- Several characters in the set.
["aaabbb", "abaa"]with"ab"gives"ab\naba". Each run is squeezed on its own. - Squeezing spaces.
["a b c"]with a single space incharsgives"a b c". - Runs that aren't squeezed.
["aabb"]with"b"gives"aab": the twoacharacters stay, becauseaisn't in the set. - Letters separated by other letters.
["mississippi"]with"sp"gives"misisipi". The runsssandppshrink, but each letter that returns later is kept. - Case.
["aAaA"]with"a"gives"aAaA". A capitalAis a different character, so there are no repeats. - Setting
prevtoo early or too late. It must be updated after the check, from the character just handled. Updating it before the test would make every character look like a repeat of itself. - Empty lines.
["", "x"]with"x"gives"\nx". - Forgetting to reset
prev. Declared outside the line loop, it would carry the last character of one line into the next.
Testing
["aaabbb", "abaa"]with"a"gives"abbb\naba".["aaabbb", "abaa"]with"ab"gives"ab\naba".["a b c"]with a single space gives"a b c".["mississippi"]with"sp"gives"misisipi".["", "x"]with"x"gives"\nx".
