我遇到需要以这种方式压缩字符串的情况:
"AAABBBCCCDDD" => "A3B3C3D3", or
"ABBCCCDDDDEEEEE" => "A1B2C3D4E5", or
"FOOFOO" => "F1O2F1O2", this one is the one I can't solve
我用JavaScript做到这一点,到目前为止我已经想到了这个:
function in_array(key, array) {
for(var x in array) {
if(array[x] == key) {
return true;
}
}
return false;
}
function compress(str) {
var str_splitted = str.split('');
var new_strings = [];
for(var x in str_splitted) {
if(!in_array(str_splitted[x], new_strings)) {
new_strings.push( str_splitted[x] );
new_strings.push( (str.split(str_splitted[x]).length - 1) );
}
}
return new_strings.join('');
}
因此,使用我的代码片段,两个示例将完美无缺,但第三个将仍然计算所有匹配的字符,因此输出:
"FOOFOO" => "F2O3", and not "F1O2F1O2"
我真的需要帮助,提示,建议和/或更好的解决方案,我感谢所有帮助我的人!
答案 0 :(得分:1)
循环遍历字符串并与前一个字符进行比较:
function compress(str) {
var last = null, cnt = 0, result = '';
for (var i = 0; i < str.length; i++) {
var c = str.charAt(i);
if (last != c) {
if (last != null) {
result += last + cnt;
}
last = c;
cnt = 0;
}
cnt++;
}
if (cnt > 0) {
result += last + cnt;
}
return result;
}
注意:使用括号按索引访问字符串在旧版IE中不起作用,因此请使用charAt
。
答案 1 :(得分:1)
function compress(str) {
var result = '',
last = null,
count = 0;
for (var i = 0; i < str.length; i++) {
var cur = str.substr(i, 1);
if (cur !== last || count == 9) {
if (last !== null) {
result += last + count;
}
last = cur;
count = 0;
}
count++;
}
// Append the last character
if (last !== null) {
result += last + count;
}
return result;
}
答案 2 :(得分:1)
function compress(str){
var result = '',
current = '',
count = 0;
for(var i = 0; i <= str.length; i++)
if(i < str.length){
if(str[i] !== current){
if(current){
result += current + count.toString();
count = 0;
}
current = str[i];
}
count++;
} else
result += current + count.toString();
return result;
}