记录区间的下标
删除该区间 并替换成 该区间对应的字符串
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param str string字符串 * @return string字符串 */ public static String compress (String str) { if(!str.contains("[")){ return str; } StringBuilder sb=new StringBuilder(str); // res 初始化 并将str赋值 int len=str.length(); char[] ch=str.toCharArray(); Deque<Integer> stack=new LinkedList<>(); for(int i=0;i<len;i++){ if(ch[i]=='['){ stack.push(i);//记录‘【’下标 }else if(ch[i]==']'){ int l=stack.pop(); int r=i; String s=str.substring(l+1,r); String res=helper(s); sb.delete(l,r+1); sb.insert(l,res); break; } } return compress(sb.toString()); } //拆分括号中的 public static String helper(String str){ StringBuilder sb=new StringBuilder(); String[] d=str.split("\\|"); int num=Integer.parseInt(d[0]); String s=d[1]; for(int i=0;i<num;i++){ sb.append(s); } return sb.toString(); } }
下面这个方法最后一个用例超时 过不去
package test; import java.util.Scanner; import java.util.*; import java.io.*; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(new BufferedInputStream(System.in)); String pass = sc.nextLine(); Stack<Character> stack = new Stack<>(); Stack<Integer> numstack = new Stack<>(); StringBuffer res = new StringBuffer(); String temp = ""; for(int i=0;i<pass.length();i++){ // 【 入栈 if(pass.charAt(i) == '[') { stack.push(pass.charAt(i)); String num_c = ""; while(pass.charAt(++i) != '|'){ num_c += pass.charAt(i); } numstack.push(Integer.valueOf(num_c)); } // 】 处理栈内 else if(pass.charAt(i) == ']'){ int num = numstack.pop(); String temp2 = ""; while(!stack.empty() && stack.peek() != '['){ temp2 = stack.pop() + temp2 ; } stack.pop(); //弹出 【 temp = ""; if(stack.empty()){ for(int j=0;j<num;j++){ temp +=temp2; } for (int k=0;k<temp.length();k++){ stack.push(temp.charAt(k)); } temp2 = ""; while(!stack.empty()){ temp2 = stack.pop() + temp2 ; } res.append(temp2); } else{ for(int j=0;j<num;j++){ temp +=temp2; } for (int k=0;k<temp.length();k++){ stack.push(temp.charAt(k)); } } } else if(stack.empty()){ res.append(pass.charAt(i)); } else if (!stack.empty()){ stack.push(pass.charAt(i)); } } System.out.println(res.toString()); } }