1678. 设计 Goal 解析器

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

请你设计一个可以解释字符串 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;
}

};

1
2
3

开辟一个新的空间,然后从第一个字符开始遍历,如果符合条件(第一种=’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

目录
相关文章
|
4天前
leetcode-1678:设计 Goal 解析器
leetcode-1678:设计 Goal 解析器
24 0
【每日一题Day19】LC1678设计Goal解析器 | 简单模拟
给你字符串 command ,返回 Goal 解析器 对 command 的解释结果。
64 0
|
2天前
|
Linux 网络安全 Windows
网络安全笔记-day8,DHCP部署_dhcp搭建部署,源码解析
网络安全笔记-day8,DHCP部署_dhcp搭建部署,源码解析
|
3天前
HuggingFace Tranformers 源码解析(4)
HuggingFace Tranformers 源码解析
6 0
|
3天前
HuggingFace Tranformers 源码解析(3)
HuggingFace Tranformers 源码解析
6 0
|
3天前
|
开发工具 git
HuggingFace Tranformers 源码解析(2)
HuggingFace Tranformers 源码解析
6 0
|
3天前
|
并行计算
HuggingFace Tranformers 源码解析(1)
HuggingFace Tranformers 源码解析
8 0
|
4天前
PandasTA 源码解析(二十三)
PandasTA 源码解析(二十三)
42 0
|
4天前
PandasTA 源码解析(二十二)(3)
PandasTA 源码解析(二十二)
34 0
|
4天前
PandasTA 源码解析(二十二)(2)
PandasTA 源码解析(二十二)
41 2

推荐镜像

更多