3612. Process String with Special Operations I
UnknownView on LeetCode
Time: O(n^2)
Space: O(n)
Problem Overview
Process the string left to right and maintain the current result as a mutable sequence.
Advertisement
Intuition
Process the string left to right and maintain the current result as a mutable sequence. Letters append. The * character removes the last character if any exist. The # character duplicates the current result by appending it to itself. The % character reverses the entire current result in place. After all characters, convert the mutable result to a string.
Algorithm
- 1Create an empty mutable result (StringBuilder).
- 2Scan characters from left to right.
- 3If the character is a lowercase English letter, append it to result.
- 4If the character is the * operator and result is not empty, remove the last character.
- 5If the character is the # operator, append the current result to itself to duplicate it.
- 6If the character is the % operator, reverse the entire current result in place.
- 7Return result as a string.
Example Walkthrough
Input: s = "a#b%*"
- 1.Start result = "".
- 2.Read a → append → "a".
- 3.Read # → duplicate → "aa".
- 4.Read b → append → "aab".
- 5.Read % → reverse → "baa".
- 6.Read * → remove last → "ba".
Output: "ba"
Common Pitfalls
- •If * appears when result is empty, do nothing.
- •For #, duplicate the current content by appending a copy of the builder, not only one character.
- •For %, reverse the whole current result, not only the next segment.
3612.cs
C#
// Approach: Simulate the operations on a mutable result string.
// Keep a StringBuilder for the current result.
// For each character in s:
// - If it is a lowercase letter, append it.
// - If it is '*', delete the last character of the current result (if it exists).
// - If it is '#', duplicate the current result by appending it to itself.
// - If it is '%', reverse the current result in place.
// Time: O(n^2) Space: O(n)
public class Solution
{
public string ProcessStr(string s)
{
StringBuilder result = new StringBuilder();
foreach (char c in s)
{
if (char.IsLetter(c))
result.Append(c);
else if (c == '*')
{
if (result.Length > 0)
result.Length = result.Length - 1;
}
else if (c == '#')
result.Append(result.ToString());
else if (c == '%')
{
// Reverse the current result string
int len = result.Length;
for (int i = 0; i < len / 2; i++)
{
char temp = result[i];
result[i] = result[len - 1 - i];
result[len - 1 - i] = temp;
}
}
// Other characters are ignored
}
return result.ToString();
}
}Advertisement
Was this solution helpful?