• 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";

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

    代码

    1. char * interpret(char * command){
    2. for (int i = 0, j = 0; i < strlen(command); ++j) {//双指针遍历
    3. switch (command[i]) {//判断当前 i 的字符
    4. case 'G' ://第一种情况
    5. command[j] = 'G';
    6. i++;
    7. break;
    8. case '(' :
    9. if(command[++i] == ')')//第二种情况
    10. {
    11. command[j] = 'o';
    12. ++i;
    13. }
    14. else//第三种情况
    15. {
    16. command[j++] = 'a';
    17. command[j] = 'l';
    18. i += 3;
    19. }
    20. break;
    21. }
    22. if (i >= strlen(command))//分隔符
    23. command[++j] = '\0';
    24. }
    25. return command;
    26. }
    27. 作者:小迅
    28. 链接:https://leetcode.cn/problems/goal-parser-interpretation/solutions/1951781/shuang-zhi-zhen-zhu-shi-chao-ji-xiang-xi-peg5/
    29. 来源:力扣(LeetCode)
    30. 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
    1. class Solution {
    2. public:
    3. string interpret(string command) {
    4. string res;
    5. for (int i = 0; i < command.size(); i++) {
    6. if (command[i] == 'G') {
    7. res += "G";
    8. } else if (command[i] == '(') {
    9. if (command[i + 1] == ')') {
    10. res += "o";
    11. } else {
    12. res += "al";
    13. }
    14. }
    15. }
    16. return res;
    17. }
    18. };
    19. 作者:小迅
    20. 链接:https://leetcode.cn/problems/goal-parser-interpretation/solutions/1951781/shuang-zhi-zhen-zhu-shi-chao-ji-xiang-xi-peg5/
    21. 来源:力扣(LeetCode)
    22. 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 相关阅读:
    React【Day4下+5】
    我人都傻了,CompletableFuture和OpenFegin一起使用竟然报错
    网络安全(黑客)工具篇
    数据预处理大全
    SizeBalanceTree
    Vue指令
    69-Java常用API:Object、Objects、StringBuilder、Math、System、BigDecimal
    【资深开发进阶专栏】
    查询sqlserver内存分配情况的SQL
    MES系统与ERP如何集成?本文告诉你答案
  • 原文地址:https://blog.csdn.net/m0_64560763/article/details/127713393