设计Goal解析器【LC1678】
You own a Goal Parser that can interpret a string
command. Thecommandconsists 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 ofcommand.
请你设计一个可以解释字符串
command的 Goal 解析器 。command由"G"、"()"和/或"(al)"按某种顺序组成。Goal 解析器会将"G"解释为字符串"G"、"()"解释为字符串"o","(al)"解释为字符串"al"。然后,按原顺序将经解释得到的字符串连接成一个字符串。给你字符串
command,返回 Goal 解析器 对command的解释结果。
以后周六不熬夜了,没起来没赶上周赛=(
-
思路:简单模拟,将结果放入StringBuilder变量中
- 使用指针i定位一个字符,该字符只有两种可能
G:在结果集末尾添加字符G(- 如果其与其后一位组成的字符串是"()":在结果集末尾添加字符
o - 如果其与其后一位组成的字符串不是"()“,那么则是”(al)":在结果集末尾添加字符
al
- 如果其与其后一位组成的字符串是"()":在结果集末尾添加字符
- 使用指针i定位一个字符,该字符只有两种可能
-
代码
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)

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

被折叠的 条评论
为什么被折叠?



