ACM模式-编程练习1

腾讯2020校招题-赛码网

方法一:

从键盘键入后,取得字符串;遍历字符串,存入StringBuider,直到获得第一个']';

获得第一个']'之后,往前读取得到重复次数,然后把目标子串重复后的结果添加到StringBuider中

继续往后存字符串,重复上面的过程

import java.util.*;
public class Main{
  public static void main(String[] args){
          Scanner in = new Scanner(System.in);
          String str = in.nextLine();
          System.out.println(uncompress(str));
      }
    private static String uncompress(String str){
        StringBuilder res = new StringBuilder();// 结果记录
        for(int i=0; i<str.length(); i++){
            char ch = str.charAt(i);
            if(ch!=']'){ // [ num | targetStr ]
                res.append(ch);
            }else{ //ch==']'
                String times;
                int endIndex = res.length()-1;
                int j = endIndex;//从endIndex往前倒,去找到数字和startIndex

                StringBuilder targetStr = new StringBuilder();//重复的目标子串
                while(res.charAt(j)!='['){
                    if(res.charAt(j)=='|'){
                        targetStr.append(res.substring(j+1));
                        endIndex = j;//数字字符串尾
                    }
                    j--;
                }
                times = res.substring(j+1,endIndex);//记录重复的次数
                int time = Integer.parseInt(times);
                StringBuilder uncompressStr = new StringBuilder();
                for(int t=0; t<time; t++){
                    uncompressStr.append(targetStr);
                }
                StringBuilder temp = new StringBuilder();
                res = temp.append(res.substring(0,j)).append(uncompressStr);
            }
        }
        return res.toString();
    }
}

 方法二:参考自灰信网编程题 - 灰信网(软件开发博客聚合)

import java.util.Collections;
import java.util.Scanner;
 
public class Main {
 
    private static String getstr(String words){
        while (words.contains("]")){
            int right = words.indexOf("]");
            int left = words.lastIndexOf("[",right);
            String repeatStr = words.substring(left + 1, right);
            String[] split = repeatStr.split("\\|");   //字符串拆分成数组
            words = words.replace("[" + repeatStr+"]",
                     String.join("", Collections.nCopies(Integer.parseInt(split[0]), split[1])));//把[***]替换成split[0]次重复的split[1]
 
        }
        return words;
    }
 
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        System.out.println(getstr(str));
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值