题解 | #牛牛的字符串解码问题#
牛牛的字符串解码问题
https://www.nowcoder.com/practice/e5658311e6d44b74872e843ba13ee290
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return string字符串 */ private int i = 0; public String decodeString (String s) { String ans = ""; // write code here for (i = 0; i < s.length();) { if (s.charAt(i) >= '0' && s.charAt(i) <= '9') { // System.out.println(s.charAt(i)); ans = ans + dfs(s); } else { ans = ans + s.charAt(i++); } } return ans; } public String dfs(String s) { String ans = ""; if (s.charAt(i) >= '0' && s.charAt(i) <= '9') { String tem = ""; int cnt = s.charAt(i) - '0'; i += 2; while (s.charAt(i) != ']' && i < s.length()) { if(s.charAt(i) >= '0' && s.charAt(i) <= '9') tem = tem + dfs(s); else tem = tem + s.charAt(i++); } while (cnt > 0) { ans = ans + tem; cnt--; } } i++; return ans; } }