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
.
Example 1:
Input: command = "G()(al)" Output: "Goal" Explanation: The Goal Parser interprets the command as follows: G -> G () -> o (al) -> al The final concatenated result is "Goal".
Example 2:
Input: command = "G()()()()(al)" Output: "Gooooal"
Example 3:
Input: command = "(al)G(al)()()G" Output: "alGalooG"
Constraints:
1 <= command.length <= 100
command
consists of"G"
,"()"
, and/or"(al)"
in some order.
设计 Goal 解析器。
请你设计一个可以解释字符串 command 的 Goal 解析器 。command 由 "G"、"()" 和/或 "(al)" 按某种顺序组成。Goal 解析器会将 "G" 解释为字符串 "G"、"()" 解释为字符串 "o" ,"(al)" 解释为字符串 "al" 。然后,按原顺序将经解释得到的字符串连接成一个字符串。
给你字符串 command ,返回 Goal 解析器 对 command 的解释结果。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/goal-parser-interpretation
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这是一道字符串操作题。一开始我想复杂了,题目中间涉及的字母一定是按顺序出现的,一定是先有了G,之后才会有 O 和 AL,只是因为 O 的数量不确定,所以需要判断一下到底有多少个。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public String interpret(String command) { 3 StringBuilder sb = new StringBuilder(); 4 int n = command.length(); 5 int i = 0; 6 while (i < n) { 7 if (command.charAt(i) == 'G') { 8 sb.append('G'); 9 i++; 10 } else if (i + 1 < n && command.charAt(i + 1) == ')') { 11 sb.append('o'); 12 i += 2; 13 } else { 14 sb.append("al"); 15 i += 4; 16 } 17 } 18 return sb.toString(); 19 } 20 }
标签:Interpretation,Goal,Parser,al,1678,字符串,command,string From: https://www.cnblogs.com/cnoodle/p/16864795.html