LeetCode in Kotlin

1750. Minimum Length of String After Deleting Similar Ends

Medium

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:

Example 3:

Input: s = “aabccabba”

Output: 3

Explanation: An optimal sequence of operations is:

Constraints:

Solution

class Solution {
    fun minimumLength(s: String): Int {
        var i = 0
        var j: Int = s.length - 1
        if (s[i] == s[j]) {
            while (i < j && s[i] == s[j]) {
                val c: Char = s[i]
                i++
                while (c == s[i] && i < j) {
                    i++
                }
                j--
                while (c == s[j] && i < j) {
                    j--
                }
            }
        }
        return if (i <= j) s.substring(i, j).length + 1 else 0
    }
}