1. 程式人生 > >算法基礎:刪除字符串中出現次數最少的字符(Golang實現)

算法基礎:刪除字符串中出現次數最少的字符(Golang實現)

cfb 出現次數 英文字母 clas har str 長度 == tracking

描寫敘述:
實現刪除字符串中出現次數最少的字符。若多個字符出現次數一樣,則都刪除。輸出刪除這些單詞後的字符串。
字符串中其他字符保持原來的順序。

輸入:
字符串僅僅包括小寫英文字母, 不考慮非法輸入,輸入的字符串長度小於等於20個字節。
輸出:
刪除字符串中出現次數最少的字符後的字符串。

例子輸入:
abcdd
例子輸出:
dd

代碼實現

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)
	//統計出現次數
	for _, v := range s {
		countMap[v]++
	}

	//查找最少次數
	var minCount int
	for _, v := range countMap {
		if minCount == 0 || v < minCount {
			minCount = v
		}
	}

	//刪除字符串中出現次數為minCount的字符
	for i := len(s) - 1; i >= 0; i-- {
		if countMap[rune(s[i])] == minCount {
			s = s[:i] + s[i+1:]
		}
	}

	return s
}


算法基礎:刪除字符串中出現次數最少的字符(Golang實現)