统计字符串中出现最多和最少的次数

本文介绍了一种使用Java实现的统计字符串中字符出现频率的方法,包括出现最多和最少的次数。通过具体示例代码展示了如何利用TreeMap进行字符计数,并获取最大最小频率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上周遇到的一道Java面试题:

 

统计字符串中出现最多和最少的次数:

代码如下:

 

package pack.java.demo;

import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
/**
 * 统计字符串中出现最多或最少的次数;
 * @author zhouhaitao
 * 2012-2-12
 */
public class CountString {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		CountString countString = new CountString();
		countString.countString("eabcdssasbccdddddsesssaaa");
	}
	
	/**
	 * 统计字符串出现最多的个数;
	 * @return
	 */
	private void countString(String str){
		Map<String,Integer> map = new TreeMap<String, Integer>();
		int count = 0;
		if(str!=null && !"".equals(str.trim())){
			//根据字符串长度循环;
			for(int i = 0;i<str.length();i++){
				count = 0;
				String tempString = str.substring(i, i+1);
				for(int x = 0;x<=i;x++){
					if(tempString.equals(str.substring(x, x+1))){
						count++;
					}
				}
				map.put(tempString, count);
			}
		}
		
		int max = Collections.max(map.values());
		int min = Collections.min(map.values());
		System.out.println("字符串中出现最多的次数是:"+max+"次,出现最少的次数是:"+min+"次");
	}
}

 

输出结果:

字符串中出现最多的次数是:7次,出现最少的次数是:2次

C++中,统计一段文本中每个单词出现的次数并找出最多最少出现的单词,可以使用`std::map`来存储每个单词及其频率,同时维护两个变量分别记录当前最大值最小值。以下是一个简单的示例: ```cpp #include <iostream> #include <string> #include <map> #include <vector> #include <algorithm> void count_words(const std::string& text) { std::map<std::string, int> word_count; std::istringstream iss(text); std::string word; while (iss >> word) { // 将所有字符转为小写,忽略标点符号 std::transform(word.begin(), word.end(), word.begin(), ::tolower); // 更新单词计数 ++word_count[word]; } if (word_count.empty()) { std::cout << "No words found." << std::endl; return; } auto max_word = *word_count.rbegin(); auto min_word = *word_count.begin(); std::cout << "Most frequent word: " << max_word.first << " (" << max_word.second << " times)\n"; std::cout << "Least frequent word: " << min_word.first << " (" << min_word.second << " times)\n"; } int main() { std::string input_text = "This is a sample text with some repeated and unique words."; count_words(input_text); return 0; } ``` 在这个示例中,我们首先创建了一个空的映射来存储单词及其频率。然后逐个读取输入字符串中的单词,并将其转换为小写形式(以便忽略大小写)。接着,我们将单词的计数加一。最后,通过查找映射的末尾元素(即频率最高的词)开头元素(频率最低的词),找到最多最少出现次数的单词。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值