0

我有一种情况需要以这种方式压缩字符串:

"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"

对于这个问题,我真的需要帮助、提示、建议和/或更好的解决方案,我感谢所有帮助我的人!

4

3 回答 3

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;
}
于 2013-06-11T07:00:57.213 回答
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;
}

演示:http: //jsfiddle.net/pjb5F/

注意:使用括号按索引访问字符串在旧版本的 IE 中不起作用,因此请使用charAt.

于 2013-06-11T06:49:42.823 回答
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;
}
于 2013-06-11T06:49:57.737 回答