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() ;
}
}