标签:ret NPU string clu not stringbu out sample line
public class Solution { /** * @param s: an expression includes numbers, letters and brackets * @return: a string */ public String expressionExpand(String s) { Stack<Object> stack = new Stack<>(); int num = 0; for (char c: s.toCharArray()) { if (Character.isDigit(c)) { num = num * 10 + c - ‘0‘; } else if (c == ‘[‘) { stack.push(Integer.valueOf(num)); num = 0; } else if (c == ‘]‘) { String newStr = popStack(stack); Integer count = (Integer) stack.pop(); for (int i = 0; i < count; i++) { stack.push(newStr); } } else { stack.push(String.valueOf(c)); } } return popStack(stack); } private String popStack(Stack<Object> stack) { // pop stack until stack is empty or get a number Stack<String> buffer = new Stack<>(); while (!stack.isEmpty() && (stack.peek() instanceof String)) { buffer.push((String) stack.pop()); } StringBuilder sb = new StringBuilder(); while (!buffer.isEmpty()) { sb.append(buffer.pop()); } return sb.toString(); } }
Given an expression s
contains numbers, letters and brackets. Number represents the number of repetitions inside the brackets(can be a string or another expression).Please expand expression to be a string.
Numbers can only appear in front of “[]”.
Example1
Input: S = abc3[a]
Output: "abcaaa"
Example2
Input: S = 3[2[ad]3[pf]]xyz
Output: "adadpfpfpfadadpfpfpfadadpfpfpfxyz"
思路:递归实现 or 非递归实现。
对于非递归实现,使用栈来解决。遇见“【“将数字放入栈中,遇见“】”将栈中的字符弹出,直到栈为空,或遇见数字,当遇见的是普通的字符,直接放入栈中。
标签:ret NPU string clu not stringbu out sample line
原文地址:https://www.cnblogs.com/FLAGyuri/p/12076969.html