• 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. };
  • 相关阅读:
    在Column中嵌入横向滚动的ListView
    muduo源码剖析之channel通道类
    STM32CUBEMX学习路线这样学就行了
    redis的原理和源码-发布订阅
    MongoDB
    感知机Perceptron
    前缀和实例1 (【模板】前缀和 )
    stream流—关于Collectors.toMap使用详解
    Python循环部分学习总结
    OpenCV变脸大法--‘让妖怪现原形‘(附源码)
  • 原文地址:https://blog.csdn.net/weixin_59179454/article/details/127715791