classSolution: defminimumDeletions(self, s: str) -> int: leftb, righta = 0, s.count('a') res = righta for c in s: if c == 'a': righta -= 1 else: leftb += 1 res = min(res, leftb + righta) return res
intminimumDeletions(char * s) { int len = strlen(s); int leftb = 0, righta = 0; for (int i = 0; i < len; i++) { if (s[i] == 'a') { righta++; } } int res = righta; for (int i = 0; i < len; i++) { char c = s[i]; if (c == 'a') { righta--; } else { leftb++; } res = MIN(res, leftb + righta); } return res; }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
var minimumDeletions = function(s) { let leftb = 0, righta = 0; for (let i = 0; i < s.length; i++) { if (s[i] === 'a') { righta++; } } let res = righta; for (let i = 0; i < s.length; i++) { const c = s[i]; if (c === 'a') { righta--; } else { leftb++; } res = Math.min(res, leftb + righta); } return res; };
funcminimumDeletions(s string)int { leftb := 0 righta := 0 for _, c := range s { if c == 'a' { righta++ } } res := righta for _, c := range s { if c == 'a' { righta-- } else { leftb++ } res = min(res, leftb+righta) } return res }
funcmin(a, b int)int { if a > b { return b } return a }
复杂度分析
时间复杂度:O(n),其中 n 是 s 的长度。需要遍历两遍 s,第一遍计算出 s 中 ``a’’ 的数量,第二遍遍历所有的间隔,求出最小需要删除的字符数。