題目:
給你一個字符串 s ,如果 s 是一個 好 字符串,請你返回 true ,否則請返回 false 。
如果 s 中出現過的 所有 字符的出現次數 相同 ,那么我們稱字符串 s 是 好 字符串。
示例 1:
輸入:s = “abacbc”
輸出:true
解釋:s 中出現過的字符為 ‘a’,‘b’ 和 ‘c’ 。s 中所有字符均出現 2 次。
示例 2:
輸入:s = “aaabb”
輸出:false
解釋:s 中出現過的字符為 ‘a’ 和 ‘b’ 。
‘a’ 出現了 3 次,‘b’ 出現了 2 次,兩者出現次數不同。
提示:
1 <= s.length <= 1000
s 只包含小寫英文字母。
解答:
class Solution:def areOccurrencesEqual(self, s: str) -> bool:# 因為字符串只包含小寫英文字母,選用數組會更好,選用字典會造成性能浪費ans = [0] * 26temp = 0for item in s:ans[ord(item) - ord('a')] += 1for i in range(26):if temp:if ans[i] != temp and ans[i] != 0:return Falseelse:temp = ans[i]return True