[LeetCode] Lexicographically Smallest String After a Swap

3216. Lexicographically Smallest String After a Swap

Given a string s containing only digits, return the

lexicographically smallest string

that can be obtained after swapping adjacent digits in s with the same parity at most once.

Digits have the same parity if both are odd or both are even. For example, 5 and 9, as well as 2 and 4, have the same parity, while 6 and 9 do not.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
bool ok(char ch, char ch2) {
if((ch ^ ch2) % 2 == 1) return false;
return ch > ch2;
}
public:
string getSmallestString(string s) {
int n = s.length();
for(int i = 1; i < n; i++) {
if(ok(s[i-1], s[i])) {
swap(s[i], s[i-1]);
return s;
}
}
return s;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2024/07/14/PS/LeetCode/lexicographically-smallest-string-after-a-swap/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.