Java 压缩字符串 [英] Java compressing Strings

查看:32
本文介绍了Java 压缩字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个接收字符串并返回字符串的方法.

I need to create a method that receives a String and also returns a String.

Ex 输入:AAABBBBCC

Ex input: AAABBBBCC

防爆输出:3A4B2C

Ex output: 3A4B2C

嗯,这很尴尬,我在今天的面试中没能做到(我正在申请初级职位),现在,在家里尝试我做了一些静态工作,我的意思是,不使用有点无用的循环,但我不知道我是否没有获得足够的睡眠时间或其他什么,但我无法弄清楚我的 for 循环应该是什么样子.这是代码:

Well, this is quite embarrassing and I couldn't manage to do it on the interview that I had today ( I was applying for a Junior position ), now, trying at home I made something that works statically, I mean, not using a loop which is kind of useless but I don't know if I'm not getting enough hours of sleep or something but I can't figure it out how my for loop should look like. This is the code:

public static String Comprimir(String texto){

    StringBuilder objString = new StringBuilder();

    int count;
    char match;

        count = texto.substring(texto.indexOf(texto.charAt(1)), texto.lastIndexOf(texto.charAt(1))).length()+1;
        match = texto.charAt(1);
        objString.append(count);
        objString.append(match);

    return objString.toString();
}

感谢您的帮助,我正在努力提高我的逻辑技能.

Thanks for your help, I'm trying to improve my logic skills.

推荐答案

遍历字符串,记住上次看到的内容.每次看到相同的字母计数.当你看到一个新字母时,把你数过的数字放到输出中,并将新字母设置为你上次看到的.

Loop through the string remembering what you last saw. Every time you see the same letter count. When you see a new letter put what you have counted onto the output and set the new letter as what you have last seen.

String input = "AAABBBBCC";

int count = 1;

char last = input.charAt(0);

StringBuilder output = new StringBuilder();

for(int i = 1; i < input.length(); i++){
    if(input.charAt(i) == last){
    count++;
    }else{
        if(count > 1){
            output.append(""+count+last);
        }else{
            output.append(last);
        }
    count = 1;
    last = input.charAt(i);
    }
}
if(count > 1){
    output.append(""+count+last);
}else{
    output.append(last);
}
System.out.println(output.toString());

这篇关于Java 压缩字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆