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.
Input: s ="45320"Output: "43520"Explanation:
`s[1] == '5'` and `s[2] == '3'` both have the same parity, and swapping them
results in the lexicographically smallest string.
To get the lexicographically smallest string, we should swap the first pair of adjacent digits with the same parity where the left digit is greater than the right. This is because only one such swap is allowed, and the earliest such swap will yield the smallest result.
classSolution {
public String smallestString(String s) {
char[] arr = s.toCharArray();
int n = arr.length;
for (int i = 0; i < n-1; i++) {
if ((arr[i]-'0')%2 == (arr[i+1]-'0')%2 && arr[i]> arr[i+1]) {
char tmp = arr[i]; arr[i]= arr[i+1]; arr[i+1]= tmp;
returnnew String(arr);
}
}
return s;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funsmallestString(s: String): String {
val arr = s.toCharArray()
for (i in0 until arr.size-1) {
if ((arr[i]-'0')%2== (arr[i+1]-'0')%2&& arr[i] > arr[i+1]) {
val tmp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = tmp
return String(arr)
}
}
return s
}
}
1
2
3
4
5
6
7
8
9
classSolution:
defsmallestString(self, s: str) -> str:
arr = list(s)
n = len(arr)
for i in range(n-1):
if int(arr[i])%2== int(arr[i+1])%2and arr[i] > arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
return''.join(arr)
return s
1
2
3
4
5
6
7
8
9
10
11
12
13
impl Solution {
pubfnsmallest_string(s: String) -> String {
letmut arr: Vec<u8>= s.bytes().collect();
let n = arr.len();
for i in0..n-1 {
if (arr[i]-b'0')%2== (arr[i+1]-b'0')%2&& arr[i] > arr[i+1] {
arr.swap(i, i+1);
return String::from_utf8(arr).unwrap();
}
}
s
}
}