提前验证抽象的正确性,尤其是边界问题在抽象中是否可以被很好的解决。然后以抽象的角度去考虑问题,简化问题。
比如双指针,提前验证可以使用双指针方法后,只需要考虑区间何时退出以及退出时的逻辑即可。
双指针原地压缩算法 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; };