Skip to content

1750. Minimum Length of String After Deleting Similar Ends 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int minimumLength(string s) {
    int i = 0;
    int j = s.length() - 1;

    while (i < j && s[i] == s[j]) {
      const char c = s[i];
      while (i <= j && s[i] == c)
        ++i;
      while (i <= j && s[j] == c)
        --j;
    }

    return j - i + 1;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int minimumLength(String s) {
    int i = 0;
    int j = s.length() - 1;

    while (i < j && s.charAt(i) == s.charAt(j)) {
      final char c = s.charAt(i);
      while (i <= j && s.charAt(i) == c)
        ++i;
      while (i <= j && s.charAt(j) == c)
        --j;
    }

    return j - i + 1;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def minimumLength(self, s: str) -> int:
    i = 0
    j = len(s) - 1

    while i < j and s[i] == s[j]:
      c = s[i]
      while i <= j and s[i] == c:
        i += 1
      while i <= j and s[j] == c:
        j -= 1

    return j - i + 1