[LeetCode] Minimum Length of String After Deleting Similar Ends

1750. Minimum Length of String After Deleting Similar Ends

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:

  1. Pick a non-empty prefix from the string s where all the characters in the prefix are equal.
  2. Pick a non-empty suffix from the string s where all the characters in this suffix are equal.
  3. The prefix and the suffix should not intersect at any index.
  4. The characters from the prefix and suffix must be the same.
  5. 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).

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int minimumLength(string s) {
int l = 0, r = s.length() - 1;
while(l < r and s[l] == s[r]) {
char target = s[l];
int L = l, R = r;
while(l <= R and s[l] == target) l++;
while(L <= r and s[r] == target) r--;
}
return max(0, r - l + 1);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/01/PS/LeetCode/minimum-length-of-string-after-deleting-similar-ends/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.