范围内最常见的字符 [英] Most frequent character in range
问题描述
我有一个长度 n
的字符串 s
。什么是最有效的数据结构/算法,用于查找范围 i..j
?
I have a string s
of length n
. What is the most efficient data structure / algorithm to use for finding the most frequent character in range i..j
?
字符串不随时间改变,我只需要重复查询,要求在 s [i]
, s [i + 1]
,..., s [j]
。
The string doesn't change over time, I just need to repeat queries that ask for the most frequent char among s[i]
, s[i + 1]
, ... , s[j]
.
推荐答案
一个数组,其中包含每个字符的出现次数。增加相应的值,同时迭代字符串一次。在执行此操作时,您可以记住数组中的当前最大值;
An array in which you hold the number of occurences of each character. You increase the respective value while iterating throught the string once. While doing this, you can remember the current max in the array; alternitively, look for the highest value in the array at the end.
伪代码
arr = [0]
for ( char in string )
arr[char]++
mostFrequent = highest(arr)
这篇关于范围内最常见的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!