#2957
Medium Algorithms Remove adjacent almost equal characters
String Dynamic Programming Greedy
53.1% acceptance
Feb 25, 2026
199
25
You are given a 0-indexed string word.
In one operation, you can pick any index i of word and change word[i] to any lowercase English letter.
Return the minimum number of operations needed to remove all adjacent almost-equal characters from word.
Two characters a and b are almost-equal if a == b or a and b are adjacent in the alphabet.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn remove_almost_equal_characters(word: String) -> i32 {
let b = word.as_bytes();
let n = b.len();
let mut ans = 0;
let mut i = 1;
while i < n {
if (b[i] as i32 - b[i - 1] as i32).abs() <= 1 {
ans += 1;
i += 2; // skip the changed position
} else {
i += 1;
}
}
ans
}
}