【Lintcode】1821. Min Deletions To Obtain String in Right Format

题目地址:

https://www.lintcode.com/problem/min-deletions-to-obtain-string-in-right-format/description

给定一个字符串 s s s,只含 A A A B B B,要求从 s s s中删除若干字符,使得 s s s成为若干 A A A后面接若干 B B B的格式。问至少要删多少个字符。

我们可以枚举分割点,在该位置所有左边的 A A A和右边的 B B B予以保留,其余都删掉,然后看最少的删除方案。代码如下:

public class Solution {
    /**
     * @param s: the string
     * @return: Min Deletions To Obtain String in Right Format
     */
    public int minDeletionsToObtainStringInRightFormat(String s) {
        // write your code here
        if (s == null || s.isEmpty()) {
            return 0;
        }
        
        int countA = 0, countB = 0;
        // 先求一下总共多少个B
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == 'B') {
                countB++;
            }
        }
    
    	// 枚举从最左端开始,后面所有的B都保留的情形
        int res = s.length() - countB;
        // 枚举s[i + 1 : ]的B都保留的情形
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == 'B') {
                countB--;
            } else {
                countA++;
            }
            
            res = Math.min(res, s.length() - countA - countB);
        }
        
        return res;
    }
}

时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值