Java&C++题解与拓展——leetcode1678. 设计Goal解析器【么的新知识】

59 阅读1分钟
每日一题做题记录,参考官方和三叶的题解

题目要求

image.png

image.png

思路:模拟

  • 就是、模拟、就是按题意走,稍微灵活一点不用判断那么全……嗯。

Java

class Solution {
    public String interpret(String command) {
        StringBuilder res = new StringBuilder();
        int n = command.length();
        for (int i = 0; i < n; ) {
            if (command.charAt(i) == 'G') {
                res.append('G');
                i += 1;
            }
            else if (i + 1 < n && command.charAt(i + 1) == ')') {
                res.append('o');
                i += 2;
            }
            else {
                res.append("al");
                i += 4;
            }
        }
        return res.toString();
    }
}
  • 时间复杂度:O(n)O(n)
  • 空间复杂度:O(n)O(n)

C++

class Solution {
public:
    string interpret(string command) {
        string res = "";
        int n = command.size();
        for (int i = 0; i < n; ) {
            if (command[i] == 'G') {
                res += 'G';
                i += 1;
            }
            else if (i + 1 < n && command[i + 1] == ')') {
                res += 'o';
                i += 2;
            }
            else {
                res += "al";
                i += 4;
            }
        }
        return res;
    }
};
  • 时间复杂度:O(n)O(n)
  • 空间复杂度:O(n)O(n)

Rust

impl Solution {
    pub fn interpret(command: String) -> String {
        command.replacen("()", "o", command.len()).replacen("(al)", "al", command.len())
    }
}
  • 时间复杂度:O(n)O(n)
  • 空间复杂度:O(n)O(n)

总结

  • 简单模拟题,刚好可以去还昨天的债。

欢迎指正与讨论!