首页 > 试题广场 >

删除字符串中出现次数最少的字符

[编程题]删除字符串中出现次数最少的字符
  • 热度指数:364148 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
实现删除字符串中出现次数最少的字符,若出现次数最少的字符有多个,则把出现次数最少的字符都删除。输出删除这些单词后的字符串,字符串中其它字符保持原来的顺序。

数据范围:输入的字符串长度满足 ,保证输入的字符串中仅出现小写字母

输入描述:

字符串只包含小写英文字母, 不考虑非法输入,输入的字符串长度小于等于20个字节。



输出描述:

删除字符串中出现次数最少的字符后的字符串。

示例1

输入

aabcddd

输出

aaddd
解题思路:1.首先,统计出每个字符在字符串中出现的次数,存放在动态数组num 中
                  2.然后,寻找数组num中的最小值
                  3.最后,若num[i]==min,则字符串中的第i个字符跳过,其他字符输出
C++实现代码:
#include<iostream>
#include<string>
using namespace std;
int findmin(int *p,int n);
int main()
{
    string str;
    while(getline(cin,str))
    {
        int len=0,i,j;
        while(str[++len]);
        int *num=new int[len];
        for(i=0;i<len;i++)
        {
            num[i]=0;
            for(j=0;j<len;j++)
            {
                if((str[i]==str[j])&&(i!=j))
                   {
                       num[i]++;
                   }
            }
        }
        int min=findmin(num,len);
        for(i=0;i<len;i++)
        {
            if(num[i]==min)
            {
                continue;
            }
            cout<<str[i];
        }
        cout<<endl;
        delete []num;
    }
    return 0;
}
int findmin(int *p,int n)
{
    int min=p[0];
    for(int i=0;i<n;i++)
    {
        if(min>p[i])
        {
            min=p[i];
        }
    }
    return min;
}
发表于 2019-08-22 08:48:43 回复(1)
import java.util.Arrays;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc=new Scanner(System.in);
        while (sc.hasNext()) {
            
        
        String target=sc.nextLine();
        String min=minString(target);
        char[] ch=target.toCharArray();
        String res="";
        for (int i = 0; i < ch.length; i++) {
            if (min.indexOf(ch[i])==-1) {
                res+=ch[i];
            }
        }
        System.out.println(res);
        }
    }
    public static String minString (String str) {
        char[] ch=str.toCharArray();
        int[] count=new int[26];
        for (int i = 0; i < ch.length; i++) {
                count[ch[i]-'a']+=1;
        }
        
        for (int i = 1; i < 13; i++) {
            char[] temp = new char[20];
            int k=0;
            int num=0;
            for (int j = 0; j < count.length; j++) {
                if (count[j]==i) {
                    num++;
                    
                    temp[k++]=(char) (j+'a');
                }
            }
            if (num>0) {
                return String.valueOf(temp);
            }
        }
        return null;
        
        
    }
}
首先想到的是 做一个count[26]的数组记录 个字母出现的次数,然后删除最小值所在字母,但是存在的问题是 最小值可能存在多个。
   为了解决可能存在多个的情况,可以从双层遍历数组,外层从1到26(事实上13就够了)为当前可能出现的最小值,内层为遍历数组。如果存在count[*]==i,则这个count[*]就是最小值,遍历完数组 统计最小值的个数num 并将该字符添加到字符串中,如果num>0跳出  返回。
   得到含最小出现次数的字符组成的字符串min,然后依次遍历原字符串字符 看是否包含在min中,在则删除
 写的比较繁琐

发表于 2018-03-06 14:15:19 回复(0)
import java.util.Scanner;

public class Main {
	
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {//注意while处理多个case
            String str = sc.nextLine();
            int[] biao = new int[26];
            int i = 0;
            for(i=0;i<str.length();++i){
                biao[str.charAt(i) - 97]++;
            }
            int min = 0;
            for(i=0;i<26;++i){
                if(biao[i]!=0){
                    min = biao[i];
                    break;
                }
            }
            for(i=0;i<26;++i){
                if(biao[i]!=0 && biao[i]<min)
                    min = biao[i];
            }
            StringBuilder sb = new StringBuilder(str);
            int j = 0;
            for(i=0; i<26; ++i){
                for(j = 0;j<str.length();++j){
                    if(biao[i] == min && str.charAt(j) == (char)(i+97)){
                        sb.delete(j, j+1);
                        str = sb.toString();
                    }
                }
            }
            System.out.println(sb.toString());
        }
    }
}


发表于 2016-09-23 14:09:19 回复(0)
笨方法
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
int main(){
	string s;
	while (cin >> s){
		int flag[26] = {};
		//memset(flag, 0, sizeof(flag));
		int length = s.size();
		for (int i = 0; i < length; ++i){
			++flag[s[i] - 'a'];
		}
		int min = 20;
		for (int i = 0; i < 26; ++i){
			if (flag[i]>0 && flag[i] < min)
				min = flag[i];
		}
		for (int i = 0; i < 26; i++){
			if (flag[i] == min)
				flag[i] = 0;
		}
		int i = 0;
		while(i < s.size()){
			if (flag[s[i] - 'a' ] == 0){
				s.erase(s.begin() + i);
				continue;
			}
			++i;
		}
		cout << s << endl;
	}

	return 0;
}

发表于 2016-08-05 21:37:20 回复(1)
get_str = list(input())
# 哈希表 key:字符 val:出现次数
hashtable = dict()
for i in get_str:
    if i in hashtable.keys():
        hashtable[i] += 1
    else:
        hashtable[i] = 1
lst_key = list(hashtable.keys())
lst_val = list(hashtable.values())
n = len(lst_key)
min_str = []
min_num = min(lst_val)
for i in range(0, n):
    if lst_val[i] == min_num:
        min_str.append(lst_key[i])
for i in range(min_num):
    for str_ in min_str:
        get_str.remove(str_)
print(''.join(get_str))

发表于 2022-07-25 19:04:45 回复(0)
import collections

s = input()
s_dict, res, minKeyLst = collections.Counter(), "", []
for c in s: s_dict[c] += 1

minValue=min(s_dict.values())
for k,v in s_dict.items():
    if v==minValue:
        minKeyLst.append(k)

for c in s:
    if c not in minKeyLst:
        res += c 
        
print(res)

发表于 2022-07-19 00:07:06 回复(0)
int cnt[26] ={0};
void solution(const string &str)
{
    for(auto i : str)
    {
        ++cnt[i - 'a'];
    }
    int minCnt = 100;
    for(int i = 0 ;i < 26; ++i)
    {
        if(cnt[i] && cnt[i] < minCnt)
            minCnt = cnt[i];
    }
    for(auto i : str)
    {
        if(cnt[i - 'a'] != minCnt)
            cout <<i;
    }
    cout << endl;
}
int main(){
    string str;
    while(cin >> str)
    {
        solution(str);
    }
}
问就是简单粗暴
发表于 2022-07-15 14:56:54 回复(0)
#include<iostream>
#include<string>
#include<vector>
using namespace std;

int main() {
    string data;
    cin >> data;

    vector<int> ret(26);
    for (int index = 0; index < data.size(); index++) {//统计各个字符出现的次数
        ret[data[index] - 'a']++;
    }

    int min = data[0] -'a';
    for (int index = 0; index < 26 ; index++) {//找出出现次数最少的字符
        if (ret[index] != 0 && ret[min] > ret[index]) {
            min = index;
        }
    }
    //出现次数最少的次数是ret[min]

    for(int i = 0 ; i < data.size() ; i++){
        if(ret[data[i] - 'a'] != ret[min]){
            cout<<data[i];
        }
    }
    
    cout<<endl;
    return 0;
}

发表于 2022-07-08 10:56:41 回复(0)
st = input()
st_lst = list(st)
st_set = set(st_lst)

st_dic ={}
def dic_str():
    for j in range(97,123):
        count = str(st.count(chr(j)))
        if count not in st_dic.keys() :
            st_dic[count] = []
        if chr(j) in st_set:
            if len(st_dic[count]) == 0 :
                st_dic[count] = chr(j)
            else:
                st_dic[count] = st_dic[count] + chr(j)
    del st_dic['0']
    lst = sorted(list(st_dic.keys()))
    st_str = st_dic[lst[0]]
    return st_str

st_str = dic_str()
st_lst1 = st_lst.copy()
for a in range(len(st_lst1)):
    if st_lst1[a] in st_str:
        st_lst.remove(st_lst1[a])
print(''.join(st_lst))

发表于 2022-07-05 10:46:34 回复(0)
# coding: utf-8
def func(strs):
    detail = {}
    s =''
    for i in sorted(strs):
        count_cur = strs.count(i)
        detail[i] = count_cur
    count_min = min(detail.values())
    for k in  detail.keys():
        if detail[k] == count_min:
            strs = strs.replace(k,"")
    print strs
if __name__ == "__main__":
    import sys
    strs = sys.stdin.readline().strip()
    func(strs)

发表于 2022-03-24 19:38:34 回复(0)
#include<stdio.h>
#include<string.h>
int main()
{
    char arr[21]={0};
    int num[124]={0},i=0;
    gets(arr);
    while(i<strlen(arr))
    {
        num[arr[i++]]++;
    }
    int min=20;
    for(int i=0;i<124;i++)
    {
        if(num[i]!=0&&num[i]<min)
            min=num[i];
    }
    for(int i=0;i<strlen(arr);i++)
    {
        if(num[arr[i]]!=min)
            printf("%c",arr[i]);
    }
    return 0;
}

发表于 2022-03-21 01:48:47 回复(0)
我怎么感觉这题目描述的有问题,如果我输入“asssbbba”,那么程序输出的应该是“sssddd”,但是那些通过的人里面有好多都是“sssddda”,而且他们都不是用的HashMap做的题目。??????
发表于 2022-03-14 11:26:05 回复(2)
#include <bits/stdc++.h>
using namespace std;

int main()
{
    string str;
    cin >> str;
    
    map<char, int> hashmap;
    for (auto c : str) {
        hashmap[c]++; // 记录每个字符出现的次数
    }
    int times = INT_MAX;
    for (auto i : hashmap) {
        times = min(times, i.second); // 找到最少次数
    }
    for (auto c: str) {
        if (hashmap[c] > times) { // 找到出现次数大于最小次数的字符,并依次输出
            cout << c;
        }
    }
    cout << endl;
    return 0;
}

发表于 2022-03-13 21:48:49 回复(0)
#include<iostream>
using namespace std;
int main(){
    string str;
    int A[26];
    for(int i=0; i<26; i++)    //谨记初始化
        A[i] = 0;
    while(cin>>str){
        for(int i=0; i<str.length(); i++){     //记录字符个数
            A[str[i]-'a'] += 1;
        }
        int min = 100;
        for(int i=0; i<26; i++){    //找到最小个数
            if(A[i]<min && A[i]!=0)
                min = A[i];
        }
        for(int i=0; i<26; i++){     //标记最小个数
            if(A[i] == min)
                A[i] = -1;
        }
        for(int i=0; i<str.length(); i++){   //输出
            if(A[str[i]-'a'] != -1)
                cout<<str[i];
        }
    }
}
发表于 2022-03-09 18:23:46 回复(0)
while True:
    try:
        a = input()
        nummin = 20
        a_new = ""
        for c in a:
            num = a.count(c)
            if num <= nummin:
                nummin = num #获取字符的最少出现次数
        for c in a:
            if a.count(c) != nummin:
                a_new += c #得到去除出现最少的字符后的字符串
        print(a_new)
    except:
        break
发表于 2022-02-24 17:47:39 回复(0)
hash排序,我还以为自己能很快呢。。
#include<stdio.h>
int main()
{
    char str[21]={0};
    int i;
    while(EOF!=scanf("%s",str))
    {
        char cnt[26]={0};
        int min = 20;
        int len = 0;
        for(i=0;str[i]!=0;i++)cnt[str[i]-'a']++;
        len = i;
        for(i=0;i<26;i++)if(cnt[i]>0 && min>cnt[i])min=cnt[i];
        for(i=0;i<len;i++)if(min!=cnt[str[i]-'a'])printf("%c",str[i]);
        printf("\n");
    }
    return 0;
}


发表于 2022-01-11 20:58:05 回复(1)
while True:
    try:
        n=list(input())
        l=[]
        for i in n:
            l.append(n.count(i))
        re=[]
        for i in range(len(l)):
            if l[i] != min(l):
                re.append(n[i])
        print(''.join(re))
    except:
        break

发表于 2021-12-16 20:20:13 回复(0)
#!usr/bin/env python3
while True:
    try:
        s = input()
        dict, res = {}, ""
        for i in s:
            if i not in dict:
                dict[i] = 1
            else:
                dict[i] += 1
        Min = min(dict.values())
        for i in s:
            if dict[i] != Min:
                res += i
        print(res)
    except:
        break
发表于 2021-11-24 15:53:09 回复(0)
// 2021.11.11
// 不熟,要多练习!!!

import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        while (scan.hasNext()){
            String str = scan.nextLine();
            Map<Character, Integer> map = new HashMap<Character, Integer>();
            for (char c:str.toCharArray()){
                if (map.containsKey(c)){
                    map.put(c,map.get(c)+1);
                }else{
                    map.put(c,1);
                }
            }
            // 在JDK中,整形类型是有范围的,最大值为Integer.MAX_VALUE,即2147483647,
            // 最小值为Integer.MIN_VALUE -2147483648
            // 遍历得到字符出现最小的次数
            int min = Integer.MAX_VALUE;
            for(Map.Entry<Character, Integer> entry:map.entrySet()){
                if (entry.getValue() < min){
                    min = entry.getValue();
                }
            }
            // 删除字符
            for (Map.Entry<Character, Integer> entry:map.entrySet()){
                if (entry.getValue() == min){
                    str = str.replace(entry.getKey() + "", "");
                }
            }
            System.out.println(str);
        }
    }
}

发表于 2021-11-11 15:41:44 回复(0)
🤣水平太low了只会这样写。。。
from collections import Counter


def test(aa):
    bb = []

    for i in aa:
        # 将字符串打散,放入列表中
        bb.append(i)
    # 统计每个字符串个数
    cc = Counter(bb)
    dd = []
    for j in bb:
        # 将cc转成列表
        dd.append([j, cc[j]])
    for i1 in range(len(dd)):
        # 将列表相同的字段替换掉
        for i2 in range(i1 + 1, len(dd)):
            if dd[i1] == dd[i2]:
                dd[i2] = 'f'
    # 列表去重
    while 'f' in dd:
        dd.remove('f')
    qqqq = []
    for i3 in range(len(dd)):
        # 将去重后的数据存入列表
        qqqq.append(dd[i3][1])
    # 查询列表最小值
    value = min(qqqq)
    ww = []
    for k2 in dd:
        # 将列表中最小值对应的字母找出来
        if k2[1] == value:
            ww.append(k2)
    for k1 in ww:
        # 将列表中最小值对应的字母删除
        while k1[0] in bb:
            bb.remove(k1[0])
    ee = ''
    for l in bb:
        ee += l
    print(ee)


while True:
    try:
        test(input())
    except:
        break


发表于 2021-10-16 23:13:28 回复(0)