小程序|给定一个字符串,请你将字符串重新编码,将连续的字符替换成“连续出现的个数+字符”。比如字符串AAAABCCDAA会被编码成4A1B2C1D2A

2017年网易真题

给定一个字符串,请你将字符串重新编码,将连续的字符替换成“连续出现的个数+字符”。比如字符串AAAABCCDAA会被编码成4A1B2C1D2A
输入例子
AAAABCCDAA
输出例子
【小程序|给定一个字符串,请你将字符串重新编码,将连续的字符替换成“连续出现的个数+字符”。比如字符串AAAABCCDAA会被编码成4A1B2C1D2A】4A1B2C1D2A
import java.util.Scanner; public class stringRepeat { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String s = scanner.next(); char[] array =s.toCharArray(); int length=s.length(); int sameCount=1; for (int i = 0; i < length-1; i++) { if (array[i]==array[i+1]){ sameCount++; } if (array[i]!=array[i+1]||i==length-2){ System.out.print(sameCount); System.out.print(array[i]); sameCount=1; } } if (array[length-2]!=array[length-1]){ System.out.print("1"+array[length-1]); } } }

    推荐阅读