Input: word ="aaaaa"Output: 2Explanation: We can change word into "a** _c_** a _**c**_ a" which does not have any adjacent almost-equal characters.It can be shown that the minimum number of operations needed to remove all adjacent almost-equal characters from word is2.
Input: word ="abddez"Output: 2Explanation: We can change word into "**_y_** bd _**o**_ ez" which does not have any adjacent almost-equal characters.It can be shown that the minimum number of operations needed to remove all adjacent almost-equal characters from word is2.
Input: word ="zyxyxyz"Output: 3Explanation: We can change word into "z _**a**_ x _**a**_ x** _a_** z" which does not have any adjacent almost-equal characters.It can be shown that the minimum number of operations needed to remove all adjacent almost-equal characters from word is3.
If two adjacent characters are almost-equal (same or consecutive in the alphabet), we must change one of them. The optimal way is to change every second character in such a pair, and skip the next character to avoid double-counting overlapping pairs.
classSolution {
public:int removeAlmostEqualCharacters(string word) {
int ans =0, n = word.size();
for (int i =0; i < n -1;) {
if (word[i] == word[i+1] || abs(word[i] - word[i+1]) ==1) {
++ans;
i +=2;
} else {
++i;
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
funcremoveAlmostEqualCharacters(wordstring) int {
ans, n:=0, len(word)
fori:=0; i < n-1; {
ifword[i] ==word[i+1] ||abs(int(word[i])-int(word[i+1])) ==1 {
ans++i+=2 } else {
i++ }
}
returnans}
funcabs(xint) int { ifx < 0 { return-x }; returnx }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
publicintremoveAlmostEqualCharacters(String word) {
int ans = 0, n = word.length();
for (int i = 0; i < n - 1;) {
if (word.charAt(i) == word.charAt(i+1) || Math.abs(word.charAt(i) - word.charAt(i+1)) == 1) {
ans++;
i += 2;
} else {
i++;
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
funremoveAlmostEqualCharacters(word: String): Int {
var ans = 0var i = 0while (i < word.length - 1) {
if (word[i] == word[i+1] || kotlin.math.abs(word[i] - word[i+1]) ==1) {
ans++ i +=2 } else {
i++ }
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defremoveAlmostEqualCharacters(self, word: str) -> int:
ans =0 i =0 n = len(word)
while i < n -1:
if word[i] == word[i+1] or abs(ord(word[i]) - ord(word[i+1])) ==1:
ans +=1 i +=2else:
i +=1return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
impl Solution {
pubfnremove_almost_equal_characters(word: String) -> i32 {
let bytes = word.as_bytes();
letmut ans =0;
letmut i =0;
while i +1< bytes.len() {
if bytes[i] == bytes[i+1] || (bytes[i] asi32- bytes[i+1] asi32).abs() ==1 {
ans +=1;
i +=2;
} else {
i +=1;
}
}
ans
}
}