ou 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.
1.新建一个StringBuffer
2.将command的数据转换成char
3.遍历数组中的元素,进行判断
4.如果元素等于’G’,添加到 StringBuffer result中
5.如果元素等于’(‘并且等于’)‘,添加到 StringBuffer result中
6.如果元素等于’(‘并且等于’a’,添加到 StringBuffer result中
7.返回result,StringBuffer result转换成String类型
replace()方法直接将字符串替换
class Solution {public String interpret(String command) {StringBuffer result = new StringBuffer();//1.新建一个StringBufferchar[]str = command.toCharArray();//2.将command的数据转换成charfor (int i = 0; i < str.length; i++) {//3.遍历数组中的元素,进行判断if(str[i]=='G') {//4.如果元素等于'G',添加到 StringBuffer result中result.append("G");}else if(str[i]=='('&& str[i+1]==')'){//5.如果元素等于'('并且等于')',添加到 StringBuffer result中result.append("o");}else if(str[i]=='('&& str[i+1]=='a'){//6.如果元素等于'('并且等于'a',添加到 StringBuffer result中result.append("al");}}return result.toString();//7.返回result,StringBuffer result转换成String类型}
}
以下代码的解题思路相同,只是StringBuffer换成了String,结果result不想要使用toString()转成String类型
class Solution {public String interpret(String command) {String result="";//1.新建一个Stringchar[] str = command.toCharArray();//2.将command的数据转换成charfor(int i=0;i//3.遍历数组中的元素,进行判断if(str[i]=='G'){//4.如果元素等于'G',添加到 String result中result+=str[i];}else if(str[i]=='(' && str[i+1]==')'){//5.如果元素等于'('并且等于')',添加到 String result中result+='o';}else if(str[i]=='(' && str[i+1]=='a'){//6.如果元素等于'('并且等于'a',添加到 String result中result+="al";}}return result; }
}
class Solution {public String interpret(String command) {return command.replace("()","o").replace("(al)","al");//直接将字符串替换 }
}