Java 压缩和解压缩字符串
如何将字符串(如Java 压缩和解压缩字符串,java,c,string,Java,C,String,如何将字符串(如“aaabbc”压缩为“a3b3c”)并对其进行解压缩,而不在处理过程中使用额外内存(主要是在C语言和Java语言中)?要进行就地编码,编码的字符串不得长于原始字符串。假设我们假设以下编码规则: 原始字符串中没有数字(因此不需要计数分隔符字符) 游程长度1从未明确编码(因此abc保持abc) 我相信有了这些假设,游程编码就不会模棱两可,也永远不会比字符串本身长。然后,以下算法(伪代码)应执行适当的编码工作: currentChar ← string[0] nextOutput
“aaabbc”
压缩为“a3b3c”
)并对其进行解压缩,而不在处理过程中使用额外内存(主要是在C语言和Java语言中)?要进行就地编码,编码的字符串不得长于原始字符串。假设我们假设以下编码规则:
- 原始字符串中没有数字(因此不需要计数分隔符字符)
- 游程长度1从未明确编码(因此
保持abc
)abc
currentChar ← string[0]
nextOutputPos ← 1
nextReadPos ← 1
count ← 1
while (nextReadPos < length of string) {
nextChar ← string[nextReadPos++];
if (nextChar == currentChar) {
count++;
} else {
if (count > 1) {
write (count as a string) to string at position nextOutputPos
nextOutputPos ← nextOutputPos + (length of count as a string)
}
string[nextOutputPos++] ← currentChar ← nextChar;
}
}
currentChar← 字符串[0]
下一个出口← 1.
nextReadPos← 1.
计数← 1.
while(nextradepos<字符串长度){
nextChar← 字符串[nextradepos++];
if(nextChar==currentChar){
计数++;
}否则{
如果(计数>1){
在nextOutputPos位置写入(作为字符串计数)字符串
下一个出口← nextOutputPos+(计数长度为字符串)
}
字符串[nextOutputPos++]← 当前字符← nextChar;
}
}
最后,编码字符串包含在
字符串的半开范围[0,nextoutpos
)中。在Java中,使用正则表达式有一种可能性:
String str = "aaabbbc"; // string to be encoded
StringBuilder sb = new StringBuilder(); // to hold encoded string
for (String s : str.split("(?<=(.))(?!\\1)")) {
sb.append(s.charAt(0));
if (s.length() > 1) // only append length if it's > 1
sb.append(s.length());
}
System.out.println(sb.toString());
String str=“aaabbbc”//要编码的字符串
StringBuilder sb=new StringBuilder();//保存编码字符串
对于(String s:str.split((?一个简单的反向扫描至少为编码部分提供了一个(似乎)很好的解决方案。我正在从右向左扫描一次,并用出现计数覆盖字符串的部分
char * enc(char * ip)
{
int r,op;
int l=strlen(ip);
r=l-1;
char curr;
op=r;
int curr_count=1,mod_curr_count;
while(r>=0)
{
curr=ip[r];
while(ip[--r]==curr)
{
curr_count++;
}
if(curr_count!=1)
{
while(curr_count)
{
mod_curr_count=curr_count%10;
ip[op--]=(char)(mod_curr_count+48);
curr_count/=10;
}
ip[op--]=curr;
curr_count=1;
}
else
{
ip[op--]=curr;
}
}
ip=ip+op+1;
return ip;
}
输入:aaaaaaaaaaaabbbffffffffffffqqqqqqqqqqcccpoii
输出:a12b3f15q18c4poi2您尝试过什么?您知道简单的运行长度压缩将扩展大多数普通文本吗?这应该是a3b3c
对吧?在Java中,您必须使用StringBuilder
,char[]
,或者类似的东西。字符串对象是不可变的,所以如果你从一个字符串开始,你将不得不使用一些额外的内存。另外,你应该如何压缩以数字开头的字符串?或者这不会发生?你怎么知道有三个字符串没有在内存中存储至少一个字符的字符?你打算在文件中读写一个字符吗?即使这样,你也必须在内存中存储两个字符来进行比较。投票结束。我是唯一一个想知道如何解压缩的人吗?
char * enc(char * ip)
{
int r,op;
int l=strlen(ip);
r=l-1;
char curr;
op=r;
int curr_count=1,mod_curr_count;
while(r>=0)
{
curr=ip[r];
while(ip[--r]==curr)
{
curr_count++;
}
if(curr_count!=1)
{
while(curr_count)
{
mod_curr_count=curr_count%10;
ip[op--]=(char)(mod_curr_count+48);
curr_count/=10;
}
ip[op--]=curr;
curr_count=1;
}
else
{
ip[op--]=curr;
}
}
ip=ip+op+1;
return ip;
}