Leetcode第1678题:设计GOAL解析器(Goal parser interpretation)

解题思路

遍历字符串command

  • 如果当前第i个字符为G,直接在返回结果中添加字符G
  • 如果当前第i个字符为(,有两种情况:
  1. i+1个字符为),转化为o.
  2. i+1个字符为a,则当前字符串会是(al),转化为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;
    }
};
posted @ 2022-11-06 20:42  hql5  阅读(32)  评论(0)    收藏  举报