删除字符串两端相同字符后的最短长度【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 )