【每日一题Day19】LC1678设计Goal解析器 | 简单模拟

本文介绍了一个简单的字符串解析器设计——Goal解析器。该解析器能够解释由G、()和(al)组成的字符串,并将其转换为G、o和al等实际字符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

设计Goal解析器【LC1678】

You own a Goal Parser that can interpret a string command. The command consists of an alphabet of "G", "()" and/or "(al)" in some order. The Goal Parser will interpret "G" as the string "G", "()" as the string "o", and "(al)" as the string "al". The interpreted strings are then concatenated in the original order.

Given the string command, return the Goal Parser’s interpretation of command.

请你设计一个可以解释字符串 commandGoal 解析器command"G""()" 和/或 "(al)" 按某种顺序组成。Goal 解析器会将 "G" 解释为字符串 "G""()" 解释为字符串 "o""(al)" 解释为字符串 "al" 。然后,按原顺序将经解释得到的字符串连接成一个字符串。

给你字符串 command ,返回 Goal 解析器command 的解释结果。

以后周六不熬夜了,没起来没赶上周赛=(

  • 思路:简单模拟,将结果放入StringBuilder变量中

    • 使用指针i定位一个字符,该字符只有两种可能
      1. G:在结果集末尾添加字符G
      2. (
        • 如果其与其后一位组成的字符串是"()":在结果集末尾添加字符o
        • 如果其与其后一位组成的字符串不是"()“,那么则是”(al)":在结果集末尾添加字符al
  • 代码

    class Solution {
        public String interpret(String command) {
            StringBuilder sb = new StringBuilder();
            int i = 0;
            int len = command.length();
            while (i < len){
                if (command.charAt(i) == 'G'){
                    sb.append('G');
                    i++;
                }else if ("()".equals(command.substring(i,i+2))){
                    sb.append('o');
                    i = i + 2;
                }else{
                    sb.append("al");
                    i = i + 4;
                }
            }
            return new String(sb);
        }
    }
    
  • 复杂度

    • 时间复杂度:O(n)O(n)O(n)
    • 空间复杂度:O(1)O(1)O(1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值