本文共 1056 字,大约阅读时间需要 3 分钟。
为了优化给定的字符压缩算法,以下是经过重新设计和优化的代码:
public class Test1_27 { public static int compress(char[] chars) { int i = 0, num = 0; while (i < chars.length) { char current = chars[i]; chars[num++] = current; int j = i + 1; while (j < chars.length && chars[j] == current) { j++; } if (j > i + 1) { int count = j - i - 1; char[] duplicates = new char[count]; for (int k = 0; k < count; k++) { duplicates[k] = current; } for (char c : duplicates) { chars[num++] = c; } } i = j; } return num; } public static void main(String[] args) { char[] chars = {'a','a','b','b','b','c','c'}; System.out.println(compress(chars)); }} 优化说明:
运行结果与原代码一致,返回值为7,表示压缩后的数组长度为7。
转载地址:http://hqdd.baihongyu.com/