Skip to content

2957. Remove Adjacent Almost-Equal Characters 👍

  • 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 removeAlmostEqualCharacters(string word) {
    int ans = 0;

    int i = 1;
    while (i < word.length())
      if (abs(word[i] - word[i - 1]) <= 1) {
        ++ans;
        i += 2;
      } else {
        i += 1;
      }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int removeAlmostEqualCharacters(String word) {
    int ans = 0;

    int i = 1;
    while (i < word.length())
      if (Math.abs(word.charAt(i) - word.charAt(i - 1)) <= 1) {
        ++ans;
        i += 2;
      } else {
        i += 1;
      }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def removeAlmostEqualCharacters(self, word: str) -> int:
    ans = 0
    i = 1
    while i < len(word):
      if abs(ord(word[i]) - ord(word[i - 1])) <= 1:
        ans += 1
        i += 2
      else:
        i += 1
    return ans