424:替换后的最长重复字符

This commit is contained in:
huangge1199 2021-09-01 16:39:01 +08:00
parent 80aa98a602
commit 047cd5b172
3 changed files with 100 additions and 0 deletions

View File

@ -0,0 +1,56 @@
//给你一个仅由大写英文字母组成的字符串你可以将任意位置上的字符替换成另外的字符总共可最多替换 k 在执行上述操作后找到包含重复字母的最长子串的长度
//
//
// 注意字符串长度 k 不会超过 10
//
//
//
// 示例 1
//
//
//输入s = "ABAB", k = 2
//输出4
//解释用两个'A'替换为两个'B',反之亦然
//
//
// 示例 2
//
//
//输入s = "AABABBA", k = 1
//输出4
//解释
//将中间的一个'A'替换为'B',字符串变为 "AABBBBA"
//子串 "BBBB" 有最长重复字母, 答案为 4
//
// Related Topics 哈希表 字符串 滑动窗口 👍 476 👎 0
package leetcode.editor.cn;
//424:替换后的最长重复字符
class LongestRepeatingCharacterReplacement {
public static void main(String[] args) {
//测试代码
Solution solution = new LongestRepeatingCharacterReplacement().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int characterReplacement(String s, int k) {
int[] num = new int[26];
int max = 0;
int index = 0;
for (int i = 0;i<s.length();i++) {
num[s.charAt(i) - 'A']++;
max = Math.max(max, num[s.charAt(i) - 'A']);
if (i - index + 1 - max > k) {
num[s.charAt(index) - 'A']--;
index++;
}
}
return s.length() - index;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,24 @@
<p>给你一个仅由大写英文字母组成的字符串,你可以将任意位置上的字符替换成另外的字符,总共可最多替换 <em>k </em>次。在执行上述操作后,找到包含重复字母的最长子串的长度。</p>
<p><strong>注意:</strong>字符串长度 和 <em>k </em>不会超过 10<sup>4</sup></p>
<p> </p>
<p><strong>示例 1</strong></p>
<pre>
<strong>输入:</strong>s = "ABAB", k = 2
<strong>输出:</strong>4
<strong>解释:</strong>用两个'A'替换为两个'B',反之亦然。
</pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入:</strong>s = "AABABBA", k = 1
<strong>输出:</strong>4
<strong>解释:</strong>
将中间的一个'A'替换为'B',字符串变为 "AABBBBA"。
子串 "BBBB" 有最长重复字母, 答案为 4。
</pre>
<div><div>Related Topics</div><div><li>哈希表</li><li>字符串</li><li>滑动窗口</li></div></div><br><div><li>👍 476</li><li>👎 0</li></div>

View File

@ -0,0 +1,20 @@
<p><strong>思路:</strong></p>
<p>将每个元素与其后的k个元素依次比较看看他们是不是相等</p>
<p>由于题目没有给出k的范围要注意先判断k的大小如果k小于等于0结果必然返回false</p>
<p><strong>代码:</strong></p>
<pre>
public boolean containsNearbyDuplicate(int[] nums, int k) {
if (k <= 0) {
return false;
}
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j <= Math.min(i + k, nums.length - 1); j++) {
if (nums[i] == nums[j]) {
return true;
}
}
}
return false;
}
</pre>