问题描述
小U得到一个只包含小写字母的字符串 S。她可以执行如下操作:每次选择字符串中两个相同的字符删除,然后在字符串末尾添加一个任意的小写字母。小U想知道,最少需要多少次操作才能使得字符串中的所有字母都不相同?
算法选择
hash + 遍历
算法思路
-
统计字符频率:
- 使用一个长度为26的数组
freq来统计字符串S中每个小写字母出现的次数。数组的索引对应字母表中的位置('a'对应0,'b'对应1,以此类推),数组的值对应该字母出现的次数。
- 使用一个长度为26的数组
-
处理重复字符:
-
遍历
freq数组,对于每个出现次数大于1的字母,执行以下操作:- 每次减少两个该字母的出现次数(模拟删除两个相同的字符)。
- 寻找
freq数组中值为0的索引,将其增加1(模拟添加一个新的字符)。 - 每执行一次这样的操作,
ans(答案计数器)就增加1。
-
-
计算最终答案:
- 最终,
ans的值就是使得字符串中的所有字母都不相同所需的最少操作次数。
- 最终,
代码展示
public class Main {
public static int solution(String S) {
// write code here
int[] freq = new int[26];
char[] cs = S.toCharArray();
int n = cs.length;
for (int i = 0; i < n; i++) {
freq[cs[i] - 'a']++;
}
int ans = 0;
// 如果freq[i] > 1 就删除他, 然后添加一个新字符
for(int i = 0; i < 26; i++){
while(freq[i] > 1){
freq[i] -= 2;
for(int j = 0; j < 26; j++){
if(freq[j] == 0){
freq[j]++;
ans++;
break;
}
}
}
}
return ans;
}
public static void main(String[] args) {
System.out.println(solution("abab") == 2);
System.out.println(solution("aaaa") == 2);
System.out.println(solution("abcabc") == 3);
}
}