Quasi FSM (Finite State Machine) problem + Vibe

Not really an FSM problem since the state isn't changing, it is just defined by the current input. Simply following the instructions should do it. Using VSCode IDE you can also engage the help of Cline or Copilot for a combo of coding and vibe coding, see below screenshot. Cheers, ACC.

Process String with Special Operations I - LeetCode

You are given a string s consisting of lowercase English letters and the special characters: *#, and %.

Build a new string result by processing s according to the following rules from left to right:

  • If the letter is a lowercase English letter append it to result.
  • '*' removes the last character from result, if it exists.
  • '#' duplicates the current result and appends it to itself.
  • '%' reverses the current result.

Return the final string result after processing all characters in s.

 

Example 1:

Input: s = "a#b%*"

Output: "ba"

Explanation:

is[i]OperationCurrent result
0'a'Append 'a'"a"
1'#'Duplicate result"aa"
2'b'Append 'b'"aab"
3'%'Reverse result"baa"
4'*'Remove the last character"ba"

Thus, the final result is "ba".

Example 2:

Input: s = "z*#"

Output: ""

Explanation:

is[i]OperationCurrent result
0'z'Append 'z'"z"
1'*'Remove the last character""
2'#'Duplicate the string""

Thus, the final result is "".

 

Constraints:

  • 1 <= s.length <= 20
  • s consists of only lowercase English letters and special characters *#, and %.


public class Solution {
    public string ProcessStr(string s) {
        string result = "";

        foreach (char c in s)
        {
            if (c >= 'a' && c <= 'z')
            {
                result += c.ToString();
            }
            else if (c == '*')
            {
                if (result.Length > 0)
                {
                    result = result.Substring(0, result.Length - 1);
                }
            }
            else if (c == '#')
            {
                result += result;
            }
            else
            {
                result = new string(result.Reverse().ToArray());
            }
        }    

        return result;
    }
}

Comments

Popular posts from this blog

Advent of Code - Day 6, 2024: BFS and FSM

Shortest Bridge – A BFS Story (with a Twist)

A non-recursive trick for subsets generation II