String Compression
程序员文章站
2022-03-12 17:10:40
...
题目
Given an array of characters, compress it in-place.
The length after compression must always be smaller than or equal to the original array.
Every element of the array should be a character (not int) of length 1.
After you are done modifying the input array in-place, return the new length of the array.
Follow up:
Could you solve it using only O(1) extra space?
答案
class Solution {
public int compress(char[] chars) {
int insert = 0;
for(int i = 0; i < chars.length; i++) {
// For each char, look right until a different char is seen
int r = i + 1;
while(r < chars.length && chars[r] == chars[i]) {
r++;
}
// place character
chars[insert++] = chars[i];
// place occurence
int count = r - i;
if(count > 1) {
String num = Integer.toString(count);
for(int j = 0; j < num.length(); j++) {
chars[insert++] = num.charAt(j);
}
}
i = r - 1;
}
return insert;
}
}
推荐阅读
-
PHP STRING 陷阱原理说明_PHP教程
-
JS基础语法---String对象
-
C#string是value type还是reference type?
-
php addslashes和mysql_real_escape_string
-
解决mysql不能插入中文Incorrect string value
-
Python的string模块中的Template类字符串模板用法
-
1366, "Incorrect string value: '\\xF0\\x9F\\x98\\x81'
-
Prototype String对象 学习_prototype
-
php中ob_gzhandler' conflicts with 'zlib output compression问题
-
PHP获取现阶段url路径的函数:QUERY_STRING、REQUEST_URI、SCRIPT.