282题 Decrypt the String解压字符串

本文介绍了一种名为DecryptString的解压字符串问题,通过XiaoQ的例子,展示如何使用压缩算法处理连续重复字符,如[3|ABC],并提供了Java代码实现。解压缩过程涉及解析字符串和替换重复部分。
摘要由CSDN通过智能技术生成

Decrypt the String解压字符串

Description
Xiao Q wanted to send a mysterious string to his friend, but he found that the string was too long, so Xiao Q invented a compression algorithm to compress the repeated part of the string, for the continuous m same string S will be compressed to [m|S] (m is an integer and 1<=m<=100). For example, the string ABCABCABC will be compressed to [3|ABC].Now Xiao A receives the string sent by Xiao Q, can you help him decompress it?

input : “HG[3|B[2|CA]]F”
output : “HGBCACABCACABCACAF”
Explain : HG[3|B[2|CA]]F −−> HG[3|BCACA]F −−> HGBCACABCACABCACAF

public class Solution {
    /**
     * @param Message: the string xiao Q sent to xiao A.
     * @return: the string after decompress
     */
   
    public String DecompressString(String Message) {
        // write your code here
        if(Message == null || Message.length() == 0){
            return null ;
        }
        StringBuilder result = new StringBuilder() ;
        for(int i = 0 ; i < Message.length() ; i++){
            if(Message.charAt(i) != ']'){
                result.append(Message.charAt(i)) ;
            }else{
                int j = result.length() -1  ;
                while(result.charAt(j) != '|'){
                    j-- ;
                }
                 String repert = result.substring(j+1) ;
                int k = j -1 ;
                while(Character.isDigit(result.charAt(k))){
                    k-- ;
                }
                int count = Integer.parseInt(result.substring(k+1 , j)) ;
                result.setLength(k) ;
                for(int l = 0 ; l < count ; l++){
                    result.append(repert) ;
                }
            }
        }

        return result.toString() ;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值