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


据题意可以知道字符串 command 一定由三种不同的字符串 “G",“()",“(al)" 组合而成,其中的转换规则如下:
由于三种不同的字符串由于模式不同,我们可以按照如下规则进行匹配:
如果当前第 i 个字符为 ‘G’,则表示当前字符串模式为 “G",转换后的结果为 “G",我们直接在结果中添加“G";
我们按照以上规则进行转换即可得到转换后的结果。
- 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)
- 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。