题源 👉 删除字符串中出现次数最少的字符_牛客题霸_牛客网 (nowcoder.com)
题目描述:
思路:
方法一:
1)使用辅助数组helper统计字符出现次数:由于字符串长度仅为【1,20】且均为小写字母(a的ASCII码为97),故对于每个出现字符,令 helper[ 字符 - ‘ a ’ ]++。
2)遍历辅助数组helper,找出出现次数最少的数min(注意helper[ i ]要大于0)。
3)遍历字符串,将出现次数最少的字符删去,即删去 helper[ 字符 - ‘ a ’ ] == min 的字符。
具体实现:
方法一:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
int[] helper = new int[26];
int min = 20;
for(int i = 0; i < s.length(); i++)
helper[s.charAt(i) - 'a']++;
for(int i = 0; i < 26; i++)
if(helper[i] > 0 && helper[i] < min)
min = helper[i];
StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.length(); i++){
if(helper[s.charAt(i) - 'a'] == min) continue;
sb.append(s.charAt(i));
}
System.out.println(new String(sb));
}
}
时间复杂度:
O(n)