本帖最后由 abcdefg11 于 2016-8-20 00:05 编辑
[Java] 纯文本查看 复制代码 public class YaSuoShuZu {
public static void main(String[] args){
String s="welcometonowcoderrrrr";
if(judgeS(s)!=0)
System.out.println(jieYaSuo(s));
if(judgeS(s)==0)
System.out.println(yaSuo(s));
}
public static int judgeS(String s){
char[] temp=new char[s.length()];//同样的先变char数组
for(int i=1;i<s.length();i++){//按照压缩规律第一位不可能是数字,所以从1开始,懒得return-1了
temp[i]=s.charAt(i);
if(temp[i]>48&&temp[i]<=57)return i;
}
return 0;
//变完了
}// !=0是已压缩数组.==0是未压缩数组
public static String yaSuo(String s){
char[] temp=new char[s.length()];
for(int i=0;i<s.length();i++){
temp[i]=s.charAt(i);
}
int count_temp=1;//初始化为1,因为调用的时候已经有一个了
String s_ok="";
char a=temp[0];//a先给第一个字符,省事
for(int i=0;i<s.length()-1;i++){
if(temp[i]==temp[i+1]){//如果等于下一个字符,则字符存下,且count_temp+1
count_temp++;
}else{
a=temp[i];
if(count_temp>1)s_ok+=a+""+count_temp;
if(count_temp==1)s_ok+=a;
count_temp=1;
}
}
if(count_temp!=1)s_ok+=temp[s.length()-1]+""+count_temp;//如果最后是重复的,还得把数字加上
if(count_temp==1)s_ok+=temp[s.length()-1];//不重复好说,只加最后一个
return s_ok;
}
public static String jieYaSuo(String s){
char[] temp=new char[s.length()];//同样的先变char数组
for(int i=0;i<s.length();i++){
temp[i]=s.charAt(i);
}
//变完了
String s_ok=temp[0]+"";//防止下标越界,从1开始
for(int i=1;i<s.length();i++){
if(temp[i]>48&&temp[i]<=57){//如果是数字,就重复这么多次
for(int j=0;j<temp[i]-49;j++){//j本来就要执行一次,所以要多减一
s_ok+=temp[i-1];
}
}else{
s_ok+=temp[i];
}
}
return s_ok;
}
}
|