ARTS Week 46
Algorithm 本周的算法题为 1156. 单字符重复子串的最大长度 如果字符串中的所有字符都相同,那么这个字符串是单字符重复的字符串。 给你一个字符串 text,你只能交换其中两个字符一次或者什么都不做,然后得到一些单字符重复的子串。返回其中最长的子串的长度。 示例 1: 输入:text = "ababa" 输出:3 实现代码如下: const maxRepOpt1 = function (text) { const count = {}; for (const char of text) { if (!count[char]) { count[char] = 0; } count[char]++; } let max_length = 0; const n = text.length; for (let i = 0; i < n; i++) { const char = text[i]; let length = 1; let j = i + 1; while (j < n && text[j] === char) { length++; j++; } if (length < count[char]) { if (j < n && text[j] !== char && j + 1 < n && text[j + 1] === char) { let k = j + 1; while (k < n && text[k] === char) { length++; k++; } if (length < count[char]) { length++; } } else { length++; } } max_length = Math.max(max_length, length); } return max_length; } 解题思路: 使用一个对象 count 来统计每个字符的出现次数。遍历字符串,将每个字符的出现次数记录在 count 中。 使用一个外层循环,从每个字符开始,向右扩展,找到当前字符的最长连续重复子串。 如果当前子串长度小于该字符的总出现次数,尝试检查子串两端是否有相同字符,或者中间是否有不同字符可以交换。 每次找到一个更长的子串时,更新 max_length。 Review Lunar New Year sees record migration in China - Breaking News English Lesson ...