

思路:模拟
- 就是、模拟、就是按题意走,稍微灵活一点不用判断那么全……嗯。
Java
class Solution {
public String interpret(String command) {
StringBuilder res = new StringBuilder();
int n = command.length();
for (int i = 0; i < n; ) {
if (command.charAt(i) == 'G') {
res.append('G');
i += 1;
}
else if (i + 1 < n && command.charAt(i + 1) == ')') {
res.append('o');
i += 2;
}
else {
res.append("al");
i += 4;
}
}
return res.toString();
}
}
- 时间复杂度:O(n)
- 空间复杂度:O(n)
C++
class Solution {
public:
string interpret(string command) {
string res = "";
int n = command.size();
for (int i = 0; i < n; ) {
if (command[i] == 'G') {
res += 'G';
i += 1;
}
else if (i + 1 < n && command[i + 1] == ')') {
res += 'o';
i += 2;
}
else {
res += "al";
i += 4;
}
}
return res;
}
};
- 时间复杂度:O(n)
- 空间复杂度:O(n)
Rust
impl Solution {
pub fn interpret(command: String) -> String {
command.replacen("()", "o", command.len()).replacen("(al)", "al", command.len())
}
}
- 时间复杂度:O(n)
- 空间复杂度:O(n)
总结