我需要创建一个接收字符串并返回字符串的方法。
防爆输入:AAABBBCCC
防爆输出:3A4B2C
好吧,这很尴尬,我在今天的面试中无法做到这一点(我正在申请初级职位),现在,我在家尝试制作一些静态工作的东西,我的意思是,不使用循环有点无用,但我不知道我是否没有获得足够的睡眠时间或其他什么,但我无法弄清楚我的 for 循环应该是什么样子。这是代码:
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();
}
感谢您的帮助,我正在努力提高我的逻辑能力。
循环遍历字符串,记住您上次看到的内容。每次您看到相同的字母计数。当您看到一个新字母时,请将您所计数的字母放入输出中,并将新字母设置为您上次看到的字母。
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());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)