[LeetCode] Change Minimum Characters to Satisfy One of Three Conditions

1737. Change Minimum Characters to Satisfy One of Three Conditions

You are given two strings a and b that consist of lowercase letters. In one operation, you can change any character in a or b to any lowercase letter.

Your goal is to satisfy one of the following three conditions:

  • Every letter in a is strictly less than every letter in b in the alphabet.
  • Every letter in b is strictly less than every letter in a in the alphabet.
  • Both a and b consist of only one distinct letter.

Return the minimum number of operations needed to achieve your goal.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int minCharacters(string a, string b) {
int res(INT_MAX), aC(0), bC(0), aL(a.length()), bL(b.length());
unordered_map<char, int> ma, mb;
for(auto& ca : a) ma[ca] += 1;
for(auto& cb : b) mb[cb] += 1;

for(auto c = 'a'; c <= 'z'; c++) {
res = min(res, aL - ma[c] + bL - mb[c]);
}

for(auto c = 'z'; c > 'a'; c--) {
res = min(res, aL - ma[c] + mb[c]);
res = min(res, bL - mb[c] + ma[c]);
ma[c - 1] += ma[c];
mb[c - 1] += mb[c];
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/12/21/PS/LeetCode/change-minimum-characters-to-satisfy-one-of-three-conditions/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.