zoukankan      html  css  js  c++  java
  • Leetcode443 压缩字符串 双指针原地压缩算法

      提前验证抽象的正确性,尤其是边界问题在抽象中是否可以被很好的解决。然后以抽象的角度去考虑问题,简化问题。

      比如双指针,提前验证可以使用双指针方法后,只需要考虑区间何时退出以及退出时的逻辑即可。

      双指针原地压缩算法 JAVA:

        public final int compress(char[] chars) {
            int write = 0, left = 0, right = 0, len = chars.length;
            while (left < len) {
                while (right < len && chars[left] == chars[right]) right++;
                int currLen = right - left;
                if (currLen <= 1) {
                    chars[write++] = chars[left++];
                    continue;
                }
                chars[write++] = chars[left];
                char[] numChars = ("" + currLen).toCharArray();
                for (char c : numChars) chars[write++] = c;
                left = right;
            }
            return write;
        }

      JS:

    /**
     * @param {character[]} chars
     * @return {number}
     */
    var compress = function (chars) {
        let write = 0, right = left = 0, len = chars.length;
        while (left < len) {
            while (right < len && chars[left] == chars[right]) right++;
            let currLen = right - left;
            if (currLen <= 1) chars[write++] = chars[left++];
            else {
                chars[write++] = chars[left];
                let currLenStr = currLen + '';
                for (let i = 0; i < currLenStr.length; i++) chars[write++] = currLenStr.charAt(i);
                left = right;
            }
        }
        return write;
    };

      

    当你看清人们的真相,于是你知道了,你可以忍受孤独
  • 相关阅读:
    toj 2819 Travel
    toj 2807 Number Sort
    zoj 2818 Prairie dogs IV
    zoj 1276 Optimal Array Multiplication Sequence
    toj 2802 Tom's Game
    toj 2798 Farey Sequence
    toj 2815 Searching Problem
    toj 2806 Replace Words
    toj 2794 Bus
    css截取字符
  • 原文地址:https://www.cnblogs.com/niuyourou/p/14383321.html
Copyright © 2011-2022 走看看