[LeetCode] 1750. Minimum Length of String After Deleting Similar Ends

CNoodle發表於2024-03-06

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).

Example 1:
Input: s = "ca"
Output: 2
Explanation: You can't remove any characters, so the string stays as is.

Example 2:
Input: s = "cabaabac"
Output: 0
Explanation: An optimal sequence of operations is:

  • Take prefix = "c" and suffix = "c" and remove them, s = "abaaba".
  • Take prefix = "a" and suffix = "a" and remove them, s = "baab".
  • Take prefix = "b" and suffix = "b" and remove them, s = "aa".
  • Take prefix = "a" and suffix = "a" and remove them, s = "".

Example 3:
Input: s = "aabccabba"
Output: 3
Explanation: An optimal sequence of operations is:

  • Take prefix = "aa" and suffix = "a" and remove them, s = "bccabb".
  • Take prefix = "b" and suffix = "bb" and remove them, s = "cca".

Constraints:
1 <= s.length <= 105
s only consists of characters 'a', 'b', and 'c'.

刪除字串兩端相同字元後的最短長度。

給你一個只包含字元 'a','b' 和 'c' 的字串 s ,你可以執行下面這個操作(5 個步驟)任意次:

  1. 選擇字串 s 一個 非空 的字首,這個字首的所有字元都相同。
  2. 選擇字串 s 一個 非空 的字尾,這個字尾的所有字元都相同。
  3. 字首和字尾在字串中任意位置都不能有交集。
  4. 字首和字尾包含的所有字元都要相同。
  5. 同時刪除字首和字尾。
    請你返回對字串 s 執行上面操作任意次以後(可能 0 次),能得到的 最短長度 。

思路

根據題目描述的意思,不難想到思路是雙指標從兩邊往中間逼近。這道題需要想清楚最後的細節,一共三種 case,
如果字串不是迴文或者中間部分不是迴文,該返回什麼長度
這種 case 最簡單,就是返回左指標和右指標的間距 + 1 即可,參考這個例子

a	b	c	d
l			r

這個 case 的長度是 4,其實就等於 right - left + 1

如果字串本身就是迴文,且是類似abba這種形式的,該返回什麼長度?
如果字串本身就是迴文但是長度是偶數,那麼最後左指標和右指標會交錯,因為 while 迴圈需要保證 left <= right

a	b	b	a
	r	l	

如果字串本身就是迴文,且是類似aba這種形式的,該返回什麼長度?
如果字串本身就是迴文但是長度是奇數,比如這種極端的例子,此時我們開始移動 l 指標的時候,最後左指標和右指標也會交錯

a	a	a
l		r

你會發現這三種 case 最後都可以返回 right - left + 1。

複雜度

時間O(n)
空間O(1)

程式碼

Java實現

class Solution {
    public int minimumLength(String s) {
		int left = 0;
		int right = s.length() - 1;
		while (left < right && s.charAt(left) == s.charAt(right)) {
			char c = s.charAt(left);
			while (left <= right && s.charAt(left) == c) {
				left++;
			}
			while (left <= right && s.charAt(right) == c) {
				right--;
			}
		}
		return right - left + 1;
    }
}

相關文章