zoukankan      html  css  js  c++  java
  • 443. String Compression 字符串压缩

    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?


    Example 1:

    Input:
    ["a","a","b","b","c","c","c"]
    
    Output:
    Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
    
    Explanation:
    "aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3".
    

    Example 2:

    Input:
    ["a"]
    
    Output:
    Return 1, and the first 1 characters of the input array should be: ["a"]
    
    Explanation:
    Nothing is replaced.
    

    Example 3:

    Input:
    ["a","b","b","b","b","b","b","b","b","b","b","b","b"]
    
    Output:
    Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].
    
    Explanation:
    Since the character "a" does not repeat, it is not compressed. "bbbbbbbbbbbb" is replaced by "b12".
    Notice each digit has it's own entry in the array.
    

    Note:

    1. All characters have an ASCII value in [35, 126].
    2. 1 <= len(chars) <= 1000.
    给定一组字符,将其压缩到原位。 压缩后的长度必须始终小于或等于原始数组。 数组的每个元素应该是长度为1的字符(不是int)。 
    修改输入数组后,返回数组的新长度。
    1. /**
    2. * @param {character[]} chars
    3. * @return {number}
    4. */
    5. var compress = function(chars) {
    6. if(!chars){
    7. return 0
    8. }
    9. if(chars.length <= 1){
    10. return chars.length;
    11. }
    12. let res = "";
    13. let count = chars.length - 1;
    14. let lastChar = chars[0];
    15. let repeat = 0;
    16. for(let i = 1; i <= count; i++){
    17. let curChar = chars[i];
    18. if(curChar == lastChar){
    19. repeat++;
    20. }
    21. if(curChar != lastChar || i == count){
    22. repeat <= 0 ? (res += lastChar) : (res += lastChar + String(repeat+1));
    23. repeat = 0;
    24. lastChar = curChar;
    25. }
    26. }
    27. if(chars[chars.length-1] != chars[chars.length-2]){
    28. res+=chars[chars.length-1];
    29. }
    30. res = res.split("");
    31. for(let i in res){
    32. chars[i] = res[i];
    33. }
    34. chars.length = res.length;
    35. return res.length;
    36. };






  • 相关阅读:
    tap事件的原理详解
    获取地理位置
    获取高度
    JSON字符串与JSON对象的区别
    zepto方法
    javascript 中 click 和onclick有什么区别呢
    oninput,onpropertychange,onchange的用法和区别
    js实时监听input中值得变化
    sql lock
    数据库SQL优化大总结
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/7784087.html
Copyright © 2011-2022 走看看