|
| 1 | +// Source : https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2021-02-12 |
| 4 | + |
| 5 | +/***************************************************************************************************** |
| 6 | + * |
| 7 | + * Given a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the |
| 8 | + * following algorithm on the string any number of times: |
| 9 | + * |
| 10 | + * Pick a non-empty prefix from the string s where all the characters in the prefix are equal. |
| 11 | + * Pick a non-empty suffix from the string s where all the characters in this suffix are equal. |
| 12 | + * The prefix and the suffix should not intersect at any index. |
| 13 | + * The characters from the prefix and suffix must be the same. |
| 14 | + * Delete both the prefix and the suffix. |
| 15 | + * |
| 16 | + * Return the minimum length of s after performing the above operation any number of times (possibly |
| 17 | + * zero times). |
| 18 | + * |
| 19 | + * Example 1: |
| 20 | + * |
| 21 | + * Input: s = "ca" |
| 22 | + * Output: 2 |
| 23 | + * Explanation: You can't remove any characters, so the string stays as is. |
| 24 | + * |
| 25 | + * Example 2: |
| 26 | + * |
| 27 | + * Input: s = "cabaabac" |
| 28 | + * Output: 0 |
| 29 | + * Explanation: An optimal sequence of operations is: |
| 30 | + * - Take prefix = "c" and suffix = "c" and remove them, s = "abaaba". |
| 31 | + * - Take prefix = "a" and suffix = "a" and remove them, s = "baab". |
| 32 | + * - Take prefix = "b" and suffix = "b" and remove them, s = "aa". |
| 33 | + * - Take prefix = "a" and suffix = "a" and remove them, s = "". |
| 34 | + * |
| 35 | + * Example 3: |
| 36 | + * |
| 37 | + * Input: s = "aabccabba" |
| 38 | + * Output: 3 |
| 39 | + * Explanation: An optimal sequence of operations is: |
| 40 | + * - Take prefix = "aa" and suffix = "a" and remove them, s = "bccabb". |
| 41 | + * - Take prefix = "b" and suffix = "bb" and remove them, s = "cca". |
| 42 | + * |
| 43 | + * Constraints: |
| 44 | + * |
| 45 | + * 1 <= s.length <= 105 |
| 46 | + * s only consists of characters 'a', 'b', and 'c'. |
| 47 | + ******************************************************************************************************/ |
| 48 | + |
| 49 | +class Solution { |
| 50 | +public: |
| 51 | + int minimumLength(string s) { |
| 52 | + char ch; |
| 53 | + int left=0, right=s.size()-1; |
| 54 | + |
| 55 | + while(left < right) { |
| 56 | + ch = s[left]; |
| 57 | + if (s[right] != ch) break; |
| 58 | + |
| 59 | + while (s[left] == ch) left++; |
| 60 | + |
| 61 | + if (left >= right ) return 0; |
| 62 | + while (s[right] == ch) right--; |
| 63 | + } |
| 64 | + |
| 65 | + return right - left + 1; |
| 66 | + |
| 67 | + } |
| 68 | +}; |
0 commit comments