【每日一题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,此时长度为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 ( 1 )
目录
相关文章
|
1月前
|
存储 编译器 C语言
函数指针&&数组指针&&数组传参的本质&&字符指针(进阶篇)
函数指针&&数组指针&&数组传参的本质&&字符指针(进阶篇)
|
1月前
|
存储 C++
使用字符指针变量和字符数组的比较
使用字符指针变量和字符数组的比较
23 0
|
1月前
|
C语言
C语言----字符数组&&指针
C语言----字符数组&&指针
31 0
|
8月前
|
存储 编译器 C语言
C语言之字符指针
C语言之字符指针
|
30天前
|
存储 C语言
字符指针变量与字符数组的比较
字符指针变量与字符数组的比较
26 3
|
30天前
|
存储 C语言
字符指针作为函数参数
字符指针作为函数参数
27 2
|
1月前
DAY-2 | 哈希表、指针与区间划分:字符种数统计问题
```markdown ## 题干 [牛客网链接](https://www.nowcoder.com/practice/eb94f6a5b2ba49c6ac72d40b5ce95f50) ## 题解 1. **查表法(哈希表)**:利用数组标记出现过的 ASCII 值小于127的字符,首次出现计数,重复则忽略。 2. **指针与区间划分(回头法)**:遍历字符串,对每个字符检查其前所有字符是否重复,重复则不计数。 ## 方法总结 - 哈希表在去重问题中非常实用,可多做相关练习。 - 使用`continue`时注意避免死循环,确保循环变量会改变。 - 多回顾此类问题以巩固理解。 ```
28 2
|
1月前
|
存储 C语言
C语言中的字符指针技术详解
C语言中的字符指针技术详解
26 0
|
1月前
|
存储 人工智能
字符指针变量和字符数组注意事项(区别)
字符指针变量和字符数组注意事项(区别)
17 0
|
1月前
|
安全 C语言 C++
字符指针做函数参数
字符指针做函数参数
17 1