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

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

问题描述

我需要创建一个接收String并返回String的方法。

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

Ex输入:AAABBBBCC

Ex input: AAABBBBCC

Ex输出: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();
}

感谢您的帮助,我正在努力提高我的逻辑技能。 / p>

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天全站免登陆