• 1678、设计Goal解析器(暴力+栈+replace)


    请你设计一个可以解释字符串 command 的 Goal 解析器 。command 由 "G"、"()" 和/或 "(al)" 按某种顺序组成。Goal 解析器会将 "G" 解释为字符串 "G"、"()" 解释为字符串 "o" ,"(al)" 解释为字符串 "al" 。然后,按原顺序将经解释得到的字符串连接成一个字符串。

    给你字符串 command ,返回 Goal 解析器 对 command 的解释结果。

    示例 1:

    输入:command = "G()(al)"
    输出:"Goal"
    解释:Goal 解析器解释命令的步骤如下所示:
    G -> G
    () -> o
    (al) -> al
    最后连接得到的结果是 "Goal"

    示例 2:

    输入:command = "G()()()()(al)"
    输出:"Gooooal"

    示例 3:

    输入:command = "(al)G(al)()()G"
    输出:"alGalooG"

    一、直接遍历

    1. char * interpret(char * command) {
    2. int len = strlen(command);
    3. char *res = (char *)malloc(sizeof(char) * (len + 1));
    4. int pos = 0;
    5. for (int i = 0; i < len; i++) {
    6. if (command[i] == 'G') {
    7. pos += sprintf(res + pos, "%s", "G");
    8. } else if (command[i] == '(') {
    9. if (command[i + 1] == ')') {
    10. pos += sprintf(res + pos, "%s", "o");
    11. } else {
    12. pos += sprintf(res + pos, "%s", "al");
    13. }
    14. }
    15. }
    16. return res;
    17. }

    二、栈模拟

    1. class Solution {
    2. public:
    3. string interpret(string command) {
    4. stack <char> stk;
    5. //遇到G,ans+=G;遇到),统计当前匹配,其他字符压栈。
    6. string ans="";
    7. for(auto x:command){
    8. int cntA = 0;
    9. if('G'==x) ans +=x;
    10. else if(')'==x) {//遇到')'弹栈匹配
    11. if(stk.top()=='l') stk.pop();
    12. if(stk.top()=='a'){
    13. stk.pop();
    14. cntA++;
    15. }
    16. if(stk.top()=='('){
    17. stk.pop();//弹出'('
    18. if(cntA) ans+="al";
    19. else ans+="o";
    20. }
    21. }
    22. else stk.push(x);//其他字符
    23. }
    24. return ans;
    25. }
    26. };

    三、 replace(java)

    replace:查找替换函数

    Java:

    1. class Solution {
    2. public String interpret(String command) {
    3. return command.replace("()","o").replace("(al)","al");
    4. }
    5. }

    C++:

    1. class Solution {
    2. public:
    3. string interpret(string command) {
    4. while(command.find("()")!=-1)
    5. {
    6. command.replace(command.find("()"),2,"o");
    7. }
    8. while(command.find("(al)")!=-1)
    9. {
    10. command.replace(command.find("(al)"),4,"al");
    11. }
    12. return command;
    13. }
    14. };
  • 相关阅读:
    Unity切换到另一个场景的时候,发现该场景变暗了
    “客户要将赠品换为折扣”,客服如何回复?
    线上问题:如何在静态方法中使用自动装配的对象(通过@PostConstruct初始化对象)
    [工业互联-8]:PLD编程快速概览、PLD五种编程语言与七款常见的PLC编程软件
    内存管理篇——线性地址的管理
    javaSE -运算符,注释,关键字(复习)
    C++ 关键字
    MySQL主从复制原理图
    Java之序列化的详细解析
    基本的SELECT语句
  • 原文地址:https://blog.csdn.net/weixin_59179454/article/details/127715791