【116】

1678. 设计 Goal 解析器
 

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

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

 

示例 1:

输入:command = "G()(al)"
输出:"Goal"
解释:Goal 解析器解释命令的步骤如下所示:
G -> G
() -> o
(al) -> al
最后连接得到的结果是 "Goal"

示例 2:

输入:command = "G()()()()(al)"
输出:"Gooooal"

示例 3:

输入:command = "(al)G(al)()()G"
输出:"alGalooG"
---------------------------------------------------------------------------------------------------
直接遍历
 1 class Solution {
 2     public String interpret(String command) {
 3         StringBuilder sb = new StringBuilder();
 4         String s = command;
 5         for(int i = 0;i < s.length();i++){
 6             char ch = s.charAt(i);
 7             if(ch == 'G'){
 8                 sb.append('G');
 9             }if(ch == '(' && s.charAt(i+1) == ')'){
10                 sb.append('o');
11             }else if(ch == '(' && s.charAt(i+1) == 'a'){
12                 sb.append("al");
13             }
14         }
15         return sb.toString();
16     }
17 }
---------------------------------------------------------------------------------------------------
调用String类的replace函数
String 和 StringBuilder中都有replace方法,今天我们来看看。
String:
String replace(char oldChar, char newChar)
用新字符newChar 替换所有的 旧字符oldChar 。

String replace(CharSequence target, CharSequence replacement)
用新字符串replacement替换所有的 旧字符串target。

String replaceAll(String regex, String replacement)
用新字符串replacement 替换所有的 正则模式匹配的串。——(替换的是模糊字串)

String replaceFirst(String regex, String replacement)
用新字符串replacement 替换第一个 正则模式匹配的串。——(替换的是模糊字串)

StringBuilder:
replace(int start,int end,String str)
用str 替换 start–end的子串。//不包括end
————————————————
版权声明:本文为CSDN博主「小码哥222」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_38737586/article/details/99224148
1 class Solution {
2     public String interpret(String command) {
3         return command.replace("()" , "o").replace("(al)", "al");
4     }
5 }

 

posted @ 2022-11-06 11:07  Wianxhlyl  阅读(55)  评论(0)    收藏  举报