String Compression
给一个string, 求如何in-place的压缩, 返回改后数组的大小. 用双指针法, 一个指针write指向数组的写入点, 另一个read指向数组的读取点.
class Solution {
public int compress(char[] chars) {
int read = 0;
int write = 0;
char c = '!';
while(read < chars.length){
if(chars[read] != c){
c = chars[read];
chars[write++] = chars[read++];
}
else{
int count = 1;
while(read < chars.length && c == chars[read]){
read++;
count++;
}
for(char t : (""+count).toCharArray()){
chars[write++] = t;
} // write count to chars
}
}
return write;
}
}