题目一
对字符串进行RLE压缩,将相邻的相同字符,用计数值和字符值来代替。例如:aaabccccccddeee,则可用3a1b6c2d3e来代替
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static String zipString3(String iniString) {
if(iniString==null||iniString.length()==0){
return "";
}
StringBuilder strB = new StringBuilder("");
char[] iniStr = iniString.toCharArray();
char pre=iniStr[0];
int count = 1;
for(int i = 1;i < iniStr.length; i++){
if(pre == iniStr[i]){
count++;
}else{
strB.append(""+count+pre);
pre = iniStr[i];
count = 1;
}
}
strB.append(""+count+pre);
return new String(strB);
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String s=in.next();
System.out.println(zipString3(s));
}
}
题目二
利用字符重复出现的次数,编写一个方法,实现基本的字符串压缩功能。比如,字符串“aabcccccaaa”经压缩会变成“a2b1c5a3”。若压缩后的字符串没有变短,则返回原先的字符串。
import java.util.*;
public class Zipper {
public String zipString(String iniString) {
if(iniString==null||iniString.length()==0){
return "";
}
StringBuilder strB = new StringBuilder("");
char[] iniStr = iniString.toCharArray();
char pre=iniStr[0];
int count = 1;
for(int i = 1;i < iniStr.length; i++){
if(pre == iniStr[i]){
count++;
}else{
strB.append(pre+""+count);
pre = iniStr[i];
count = 1;
}
}
strB.append(pre+""+count);
if(strB.toString().length() >= iniString.length()){
return iniString;
}
return strB.toString();
}
}
StringBuilder str = new StringBuilder();
int curSum = 1;
char curChars = chars[0];
for (int i = 0;i < chars.length-1; i++){
if (chars[i] == chars[i+1]){
curSum ++;
curChars = chars[i];
}else{
str.append(curChars);
if (curSum > 1){
str.append(curSum);
}
curSum = 1;
curChars = chars[i+1];
}
}
if (curSum > 1){
str.append(curChars);
str.append(curSum);
}else{
str.append(curChars);
}