LeetCode·每日一题·1678.设计 Goal 解析器·双指针

作者:小迅
链接:https://leetcode.cn/problems/goal-parser-interpretation/solutions/1951781/shuang-zhi-zhen-zhu-shi-chao-ji-xiang-xi-peg5/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 

题目

 

示例

 

思路

据题意可以知道字符串 command 一定由三种不同的字符串 “G",“()",“(al)" 组合而成,其中的转换规则如下:

  • “G" 转换为 “G";
  • “() 转换为 “o";
  • “(al) 转换为 “al";

由于三种不同的字符串由于模式不同,我们可以按照如下规则进行匹配:

如果当前第 i 个字符为 ‘G’,则表示当前字符串模式为 “G",转换后的结果为 “G",我们直接在结果中添加“G";

  • 如果当前第 i 个字符为 ‘(’,则表示当前字符串模式可能为 “()" 或 “(al)";
  • 如果第 i+1 个字符为 ‘)’,则当前字符串模式为 “()",我们应将其转换为 “o";
  • 如果第 i+1 个字符为 ‘a’,则当前字符串模式为 “(al)",我们应将其转换为 “al";

我们按照以上规则进行转换即可得到转换后的结果。

代码

char * interpret(char * command){
    for (int i = 0, j = 0; i < strlen(command); ++j) {//双指针遍历
        switch (command[i]) {//判断当前 i 的字符
            case 'G' ://第一种情况
                command[j] = 'G';
                i++;
            break;
            case '(' :
                if(command[++i] == ')')//第二种情况
                {
                    command[j] = 'o';
                    ++i;
                }
                else//第三种情况
                {
                    command[j++] = 'a';
                    command[j] = 'l';
                    i += 3;
                }
            break;
        }
        if (i >= strlen(command))//分隔符
            command[++j] = '\0';
    }
    return command;
}

作者:小迅
链接:https://leetcode.cn/problems/goal-parser-interpretation/solutions/1951781/shuang-zhi-zhen-zhu-shi-chao-ji-xiang-xi-peg5/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

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;
    }
};


作者:小迅
链接:https://leetcode.cn/problems/goal-parser-interpretation/solutions/1951781/shuang-zhi-zhen-zhu-shi-chao-ji-xiang-xi-peg5/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值