Start learning free

LESSON 399 OF 413 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: tr v4 — Squeeze Repeats (-s) in C#

Practice

Build a version of the Unix tr -s command. Given a list of lines and a string chars, collapse consecutive runs of any character that appears in chars to a single occurrence. Other characters are unchanged. Return the lines joined by newline characters (\n).

Notes: chars is a non-empty ASCII string whose characters are taken literally (no ranges). Only runs of the same character from chars are collapsed; all other characters, and runs of characters not in chars, stay as they are. Upper and lower case are different characters. Lines may be empty.

Function signature:

public string TrSqueeze(List<string> lines, string chars)

Example:

Input: lines = ["aaabbb", "abaa"], chars = "a"

Output: "abbb\naba"

When printed:
abbb
aba

Put each char of chars into a HashSet<char>. Walk each line tracking char prev = '\0'; skip the current char only if it's in the set AND equals prev.

The full solution:
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);
    }
}

STEP 1 OF 15
    Ctrl + Enter to check

    Tr V4 in C#

    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free