力扣题目链接:https://leetcode.cn/problems/goal-parser-interpretation/
请你设计一个可以解释字符串 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 <= 100command 由 "G"、"()" 和/或 "(al)" 按某种顺序组成我们直接按照规则进行模拟即可
从前到后遍历字符串:
遇到G就将G添加到答案字符串中
遇到(就看下一个字符是)还是a
),就说明遇到了(),将o添加到答案字符串中,并将“遍历指针”后移一位())(al),将al添加到答案字符串中,并将“遍历指针”后移三位(al))时间复杂度 O ( n ) O(n) O(n),其中 n n n是原始字符串的长度
空间复杂度 O ( 1 ) O(1) O(1)
class Solution {
public:
string interpret(string& command) {
string ans;
for (int i = 0; i < command.size(); i++) {
if (command[i] == 'G') {
ans += 'G';
}
else { // (
if (command[i + 1] == ')') // ()
ans += 'o', i += 1;
else // (al)
ans += "al", i += 3;
}
}
return ans;
}
};
同步发文于CSDN,原创不易,转载请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/127712058