Golang is programmed to delete the least number of characters in a string

  • 2020-06-01 10:01:50
  • OfStack

The example in this article describes a programming method for Golang to delete the least frequently occurring characters in a string. I will share it with you for your reference as follows:

Description:

To delete the least number of characters in the string, if multiple characters appear 1, they are deleted. Output the string after the words are removed, and the other characters in the string remain in the same order.

Input:

The string contains only lowercase letters, regardless of illegal input, and the length of the input string is less than or equal to 20 bytes.

Output:

Removes the string after the least frequent occurrence of the character in the string.

Sample input:

abcdd

Sample output:

dd

Code implementation:

package huawei
import (
    "fmt"
)
func Test4Base() {
    s := "abcfbcca"
    result := deleteMinChars(s)
    fmt.Println(result)
}
func deleteMinChars(s string) string {
    countMap := make(map[rune]int, 0)
    // Statistical frequency of occurrence
    for _, v := range s {
        countMap[v]++
    }
    // Minimum number of lookups
    var minCount int
    for _, v := range countMap {
        if minCount == 0 || v < minCount {
            minCount = v
        }
    }
    // The number of occurrences in the delete string is minCount The character of
    for i := len(s) - 1; i >= 0; i-- {
        if countMap[rune(s[i])] == minCount {
            s = s[:i] + s[i+1:]
        }
    }
    return s
}

I hope this article has been helpful to you in the programming of Go language.


Related articles: