【每日一题Day70】LC1750删除字符串两端相同字符后的最短长度 | 双指针模拟+贪心

删除字符串两端相同字符后的最短长度【LC1750】

Given a string s consisting only of characters ‘a’, ‘b’, and ‘c’. You are asked to apply the following algorithm on the string any number of times:

Pick a non-empty prefix from the string s where all the characters in the prefix are equal.
Pick a non-empty suffix from the string s where all the characters in this suffix are equal.
The prefix and the suffix should not intersect at any index.
The characters from the prefix and suffix must be the same.
Delete both the prefix and the suffix.
Return the minimum length of s after performing the above operation any number of times (possibly zero times).

感觉和上周周赛有点像,不过更简单一点,每种字符至少取K个

  • 思路:使用双指针定位左右两端的字符,当左右两端的字符相同时,删除所有能够删除的相同字符[有一点贪心],将左指针右移,将右指针左移;当左右两端字符不相同时,不能够进行删除操作,最后返回左右指针中间的字符串长度即可

  • 实现

    注意:边界的处理,当字符串全都能够被删除时,右边界会移动到 j = i − 1 j=i-1 j=i1,此时长度为0

    class Solution {
        public int minimumLength(String s) {
            int n = s.length();
            int i = 0, j = n - 1;
            while (i < j && s.charAt(i) == s.charAt(j)){
                char c = s.charAt(i);
                while (i < j && c == s.charAt(i)){
                    i++;
                }
                while (i <= j && c == s.charAt(j)){
                    j--;
                }
            }
            return j - i + 1;
    
        }
    }
    
    • 复杂度
      • 时间复杂度: 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、付费专栏及课程。

余额充值