如果当前第 i 个字符为 `G’,则表示当前字符串模式为 G",转换后的结果为 G”,我们直接在结果中添加 ``G”;
如果当前第 i 个字符为 `(‘,则表示当前字符串模式可能为 ()" 或 (al)”;
如果第 i+1 个字符为 `)’,则当前字符串模式为 ()",我们应将其转换为 o”;
如果第 i+1 个字符为 `a’,则当前字符串模式为 (al)",我们应将其转换为 al”;
我们按照以上规则进行转换即可得到转换后的结果。
代码
[sol1-Python3]
1 2 3 4 5 6 7 8 9
classSolution: definterpret(self, command: str) -> str: res = [] for i, c inenumerate(command): if c == 'G': res.append(c) elif c == '(': res.append('o'if command[i + 1] == ')'else'al') return''.join(res)
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public: string interpret(string command){ string res; for (int i = 0; i < command.size(); i++) { if (command[i] == 'G') { res += "G"; } elseif (command[i] == '(') { if (command[i + 1] == ')') { res += "o"; } else { res += "al"; } } } return res; } };
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { public String interpret(String command) { StringBuilderres=newStringBuilder(); for (inti=0; i < command.length(); i++) { if (command.charAt(i) == 'G') { res.append("G"); } elseif (command.charAt(i) == '(') { if (command.charAt(i + 1) == ')') { res.append("o"); } else { res.append("al"); } } } return res.toString(); } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
publicclassSolution { publicstringInterpret(string command) { StringBuilder res = new StringBuilder(); for (int i = 0; i < command.Length; i++) { if (command[i] == 'G') { res.Append("G"); } elseif (command[i] == '(') { if (command[i + 1] == ')') { res.Append("o"); } else { res.Append("al"); } } } return res.ToString(); } }
var interpret = function(command) { let res = ''; for (let i = 0; i < command.length; i++) { if (command[i] === 'G') { res += 'G'; } elseif (command[i] === '(') { if (command[i + 1] === ')') { res += 'o'; } else { res += 'al'; } } } return res; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
funcinterpret(command string)string { res := &strings.Builder{} for i, c := range command { if c == 'G' { res.WriteByte('G') } elseif c == '(' { if command[i+1] == ')' { res.WriteByte('o') } else { res.WriteString("al") } } } return res.String() }