mirror of
https://github.com/jrpie/Launcher.git
synced 2025-06-28 20:05:30 +02:00
Improve performance of occurrence counting
Changed the algorithm for occurrence counting to improve performance. Previously it was based on expensive string manipulations and checks. The new approach is based on a frequency map with fewer iterations.
This commit is contained in:
parent
90c6147fc9
commit
911bfac162
1 changed files with 10 additions and 6 deletions
|
@ -23,13 +23,17 @@ fun isSubsequent(text: String, search: String): Boolean {
|
|||
* as often as it occurs in `search`.
|
||||
*/
|
||||
fun countOccurrences(text: String, search: String): Int {
|
||||
val foundCharacters = mutableListOf<Char>()
|
||||
var mutText = text
|
||||
val frequencies = mutableMapOf<Char, Int>()
|
||||
for (char in text) {
|
||||
frequencies[char] = frequencies.getOrElse(char) { 0 } + 1
|
||||
}
|
||||
var result = 0
|
||||
for (char in search) {
|
||||
if (mutText.contains(char)) {
|
||||
foundCharacters.add(char)
|
||||
mutText = mutText.replaceFirst(char.toString(), "")
|
||||
val charFrequency = frequencies[char] ?: 0
|
||||
if (charFrequency > 0) {
|
||||
result++
|
||||
frequencies[char] = charFrequency - 1
|
||||
}
|
||||
}
|
||||
return foundCharacters.size
|
||||
return result
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue