1678. 设计 Goal 解析器

请你设计一个可以解释字符串 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 <= command.length <= 100
command 由 “G”、"()" 和/或 “(al)” 按某种顺序组成

class Solution {
    
    
public:
    string interpret(string command) {
    
    
        string res;
        for (int i = 0; i < command.size(); i++) {
    
    
            if (command[i] == 'G') 
            {
    
    
                res += "G";
            } 
            else if (command[i] == '(')
             {
    
    
                if (command[i + 1] == ')')
                 {
    
    
                    res += "o";
                } 
                else 
                {
    
    
                    res += "al";
                }
            }
        }
        return res;
    }
};

开辟一个新的空间,然后从第一个字符开始遍历,如果符合条件(第一种=’G’ 第二种=’o’ 第三种=’al’)连接在ret后面即可。

char * interpret(char * command){
    
    
    char *arr_result = (char*)malloc(sizeof(char)*(strlen(command)+1));//strlen()里可以放一个字符指针
    char *p = command;
    int i=0;
    while(p[i]!='\0'){
    
    
        if(p[i] == 'G')
            arr_result[i++] = 'G';
        else if(p[i] == '(')
            if(p[i+1] == ')'){
    
    
              arr_result[i++] = 'o';
              p += 1;
            }
            else{
    
    
              arr_result[i++] = 'a';
              arr_result[i++] = 'l';
              p += 2;
            }
    }
        arr_result[i] = '\0';
    return arr_result;
}

() -> o
字符从两个变成一个,所以要进行p++
(al) -> al
字符从四个变成两个,所以要进行p+=2

猜你喜欢

转载自blog.csdn.net/2202_75623950/article/details/130621862