设计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.
请你设计一个可以解释字符串 command 的 Goal 解析器 。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 ( 1 )