1678. 设计 Goal 解析器(java / c / c++ / python / go / rust)

121 阅读1分钟

「这是我参与2022首次更文挑战的第8天,活动详情查看:2022首次更文挑战」。


1678. 设计 Goal 解析器:

请你设计一个可以解释字符串 commandGoal 解析器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)" 按某种顺序组成

分析

  • 面对这道算法题目,我陷入了沉思,同样是简单题,但还真的不是一样简单。
  • 有replace接口的,这题完全没有什么可考虑的。
  • 如果是自己处理,"G"很容易区分出来,只有"()""(al)"仅靠第一个字母无法区分,所以需要去取一下后面的字符。

题解

java

class Solution {
    public String interpret(String command) {
        command = command.replace("(al)", "al").replace("()", "o");
        return command;
    }
}

c

char * interpret(char * command){
    int len = strlen(command);
    char *ans = (char *) malloc((len + 1) * sizeof(char));
    int i = 0;
    while (*command) {
        if (*command == 'G') {
            ans[i++] = 'G';
            ++command;
        } else if (*(command + 1) == ')') {
            ans[i++] = 'o';
            command += 2;
        } else {
            ans[i++] = 'a';
            ans[i++] = 'l';
            command += 4;
        }
    }
    ans[i] = '\0';
    return ans;
}

c++

class Solution {
public:
    string interpret(string command) {
        string ans;

        int i = 0;
        while (i < command.length()) {
            if (command[i] == 'G') {
                ans += 'G';
                ++i;
            } else if (command[i + 1] == ')') {
                ans += 'o';
                i += 2;
            } else {
                ans += "al";
                i += 4;
            }
        }

        return ans;
    }
};

python

class Solution:
    def interpret(self, command: str) -> str:
        return command.replace('(al)', 'al').replace('()', 'o')
        

go

func interpret(command string) string {
    command = strings.ReplaceAll(command, "(al)", "al")
	command = strings.ReplaceAll(command, "()", "o")
	return command
}

rust

impl Solution {
    pub fn interpret(command: String) -> String {
        command.replace("(al)", "al").replace("()", "o")
    }
}

在这里插入图片描述


原题传送门:https://leetcode-cn.com/problems/goal-parser-interpretation/


非常感谢你阅读本文~
放弃不难,但坚持一定很酷~
希望我们大家都能每天进步一点点~
本文由 二当家的白帽子:https://juejin.cn/user/2771185768884824/posts 博客原创~